Python Tips and Tricks

The following is a list of useful Python tricks and Tips.

String

Combine a list of strings to a single string
result = ''.join(strings)
Interpolate variable within strings
name = 'Jack'
age = 88
msg = "%s is %d years old" % (name, age)

Dictionary

Use in wherever possible
for key in d:
    print key

in is generally faster, and this pattern works for items in arbitrary containers.

Use .keys() when mutating the dictionary
for key in d.keys():
    d[str(key)] = d[key]
Word count
from collections import defaultdict
counts = defaultdict(int) # default value for int is 0
for key in d:
    counts[key] += 1
Iterate over keys and values
for (key, val) in d.iteritems():
    print key, val
building dictionary from two lists
d = dict(zip(l1, l2))

List

Use map or filter to apply functions to lists
# Worse:
strings = []
for d in data:
    strings.append(str(d))

# Better:
strings = map(str, data)

These functions make code much shorter and much faster, since the loop takes place entirely in the C API and never has to bind loop variables to Python objects.

Iterate with indices
l = ['a', 'b', 'c']
for (i, val) in enumerate(l):
    print i, val # i will be zero-based integer index for each element in l.

enumerate function actually returns an iterator

List comprehension vs generator expressions
# use a list comprehension when a computed list is the desired end result
l = [num * num for num in range(1, 101)]
# use a generator expression when the computed list is just an intermediate step
total = sum(num * num
            for num in xrange(1, 1000000000))

Tuple

Unpack tuples during iteration
for (photo_name, (width, height)) in photos:
    # do sth with photo_name, width, and height

Others

Infinite loop
while 1: # This is the conversion.
Catch errors vs if statements
Worse:
#check whether int conversion will raise an error
if not isinstance(s, str) or not s.isdigit:
    return None
elif len(s) > 10:    #too many digits for int conversion
    return None
else:
    return int(str)

Better:
try:
    return int(str)
except (TypeError, ValueError, OverflowError): #int conversion failed
    return None
Swap without using temporary variables
a, b = b, a # this is the implicit tuple unpacking
create a new sorted list vs in-place sort
l = [3, 2, 4]
# create a new sorted list
new_l = sorted(l)
# in-place sort
l.sort()
sort with keys
# sort list based on the second column first, then fourth column
def my_key(item):
    return (item[1], item[3])
to_sort.sort(key=my_key)

References