Effective Python 11 - 15

Click here for the first post, which contains the context of this series.

Item #11: Know how to slice sequences.

>>> [1, 2, 3, 4, 5][1 : 3], [1, 2, 3, 4, 5][: -2]
([2, 3], [1, 2, 3])

Item #12: Avoid striding and slicing in a single expression.

Avoid

>>> [1, 2, 3, 4, 5][2::2]
[3, 5]

This does not work for all types, e.g., UTF-8.

Item #13: Prefer catch-all unpacking over slicing.

Let A = [1, 2, 3, 4]. Prefer

first, second, *rest = A

over

first, second, rest = A[0], A[1], A[2 :]

Item #14: Sort by complex criteria using the key parameter.

my_list.sort() does not work if the objects do not implement __lt__. This can be circumvented as follows: my_list.sort(key=lambda object: object.property), where property hopefully implements __lt__, e.g., it is an integer, a string, or user-defined.

Item #15: Be cautious when relying on dict insertion ordering.

A Python dictionary my_dict is implemented as a hash table. Therefore, for key in my_dict iterates its keys in an arbitrary order. Newer versions of Python do not have this problem.