The following is a list of useful Python tricks and Tips.
result = ''.join(strings)
name = 'Jack' age = 88 msg = "%s is %d years old" % (name, age)
for key in d: print key
in is generally faster, and this pattern works for items in arbitrary containers.
for key in d.keys(): d[str(key)] = d[key]
from collections import defaultdict counts = defaultdict(int) # default value for int is 0 for key in d: counts[key] += 1
for (key, val) in d.iteritems(): print key, val
d = dict(zip(l1, l2))
# 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.
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
# 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))
for (photo_name, (width, height)) in photos: # do sth with photo_name, width, and height
while 1: # This is the conversion.
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
a, b = b, a # this is the implicit tuple unpacking
l = [3, 2, 4] # create a new sorted list new_l = sorted(l) # in-place sort l.sort()
# 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)