Python Tips and Tricks

Contents

Build strings using str.join not +

Suppose you wanted to build the string '0--1--2--3--4'. You could use a for-loop like this:

result = ''
for i in range(5):
    result = result + str(i)
    if i < 4:
        result = result + '--'

But there are at least three problems here: (1) it can be written more succinctly, (2) it uses `+` instead of `str.join` and worst of all, (3) it has to test if i is the last item before adding the separator --.

The better way to build a string with a repeated separator is to use str.join:

>>> '--'.join(map(str,range(5)))
'0--1--2--3--4'

'--' is a string. '--'.join is the string's join method. The join method expects one argument, which is a sequence of strings.

>>> map(str, range(5))
['0', '1', '2', '3', '4']

Dictionaries within dictionaries

Dr. Norvig showed this amazing trick for nesting dictionaries as values within other dictionaries to an arbitrary depth in this forum post:

import collections
def tree(): return collections.defaultdict(tree)

Build lists

duplicate - change [5] to the list and 5 to the multiplier you need

>>> [5]*5
[5, 5, 5, 5, 5]

comprehension - change x**2 to the value and range(5) to the list you need

>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]

mapping - change int to the function and ['1', '2', '3'] to the list you need

>>> map(int, ['1', '2', '3'])
[1, 2, 3]