Python Cool Stuff

A collection of snippets and well-known techniques to make your code more concise & elegant.

Ternary Expressions

if ... else can be used to write a ternary expression. It does exactly what is sounds like: assign 3 to x if y is 1. The parens are not needed but they are good for readability.

>>> y = 0
>>> x = 3 if (y == 1) else 2
>>> print(x)
2

The Zen of Python

Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Chained Comparisons

Chained comparisons are faster and prettier than the normal way:

>>> if 10 <= f(x) < 150:
...     g(x)

Looping over two collections

zip (or izip for better performance) let you iterate over two collections at the same time by returning tuples of their corresponding values:

>>> names = ['john', 'adam', 'betty']
>>> drinks = ['coffee', 'tea', 'milk']
>>>
>>> for name, drink in zip(names, drinks):
...     print(name + ' -> ' + drink)
...
john -> coffee
adam -> tea
betty -> milk

You can even construct a dict from these two lists with zip/izip:

>>> d = dict(izip(names, drinks))
{'john': 'coffee', 'adam': 'tea', 'betty': 'milk'}

Looping backwards

With reversed you get an iterator over the backwards of the sequence you passed in:

>>> s = [1, 2, 3, 4, 5]
>>> for i in reversed(s):
...     print i
...
5 4 3 2 1

SimpleHTTPServer

Want to know how your site looks on the server? Just launch the python built-in SimpleHTTPServer module:

$ python -m SimpleHTTPServer
$ Serving HTTP on 0.0.0.0 port 8000 ...

defaultdict

With defaultdict you'll never get a KeyError. Instead, it will always return the factory function you passed in:

>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

dict comprehension

Likewise list, there's a way to create dictionary using the 'comprehension-way':

>>> { i : chr(65+i) for i in range(26) }

This will prompt:

>>> {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}
Fork me on GitHub