Python Code Style

Unpacking

1
2
3
4
5
6
7
8
9
10
for index, item in enumerate(some_list):
# do something with index and item

a, b = b, a
a, (b, c) = 1, (2, 3)
# in Python 3:
a, *rest = [1, 2, 3]
# a = 1, rest = [2, 3]
a, *middle, c = [1, 2, 3, 4]
# a = 1, middle = [2, 3], c = 4

Create an ignored variable

if you need to assign something but will not need that variable, use__:

1
2
filename = 'foobar.txt'
basename, __, ext = filename.rpartition('.')

####Create a length-N list of the same thing

1
2
four_nones = [None] * 4
four_lists = [[] for __ in xrange(4)]

Short ways to manipulate lists

1
2
3
4
5
6
7
8
9
10
# filter elements greater than 4
a = [3, 4, 5]
b = [i for i in a if i > 4]
# or:
b = filter(lambda x: x > 4, a)
# add three to all list members
a = [3, 4, 5]
a = [i + 3 for i in a]
# or:
a = map(lambda i : i + 3, a)

Line continuations

use parenthesis rather than backslash, an unexpected white space after the backslash will break the code.