Idiomatic Python: the very basic stuff

Check for something

if 'h' in 'hello': print 'y'
if something in someset: go()

Building strings in linear time

truth = ''.join(('why', 'so', 'serious'))
# 'whysoserious'

String Formatting

print '{0} so {1}?'.format('Why', 'serious')

Enumerate

>>> for c in enumerate('no'):
...     print c
(0, 'n')
(1, 'o')

>>> for pos, value in enumerate(['one', 'more', 'time']):
...     if pos < 1 or pos >= 2: print value
one
time

List comprehension

a = [1,2,3,4]
b = [x for x in a]

[i * 3 for i in data if i > 10]

# flattening a list:
[ x for y in l for x in y ]

Zip

d = dict(zip(keys, values))

Using the context manager

This is bad: if an exception occurs, the file handle is never closed.

f = open(path_to_file, 'r')
for line in f.readlines():
    if some_function_that_throws_exceptions(line):
        # do something
f.close()

Use with instead:

with open(path_to_file, 'r') as f:
    for line in f:
        if some_function_that_throws_exceptions(line):
            # do something
# No need to explicitly call 'close'