Short (and useful) python snippets [closed] Short (and useful) python snippets [closed] python python

Short (and useful) python snippets [closed]


I like using any and a generator:

if any(pred(x.item) for x in sequence):    ...

instead of code written like this:

found = Falsefor x in sequence:    if pred(x.n):        found = Trueif found:    ...

I first learned of this technique from a Peter Norvig article.


Initializing a 2D list

While this can be done safely to initialize a list:

lst = [0] * 3

The same trick won’t work for a 2D list (list of lists):

>>> lst_2d = [[0] * 3] * 3>>> lst_2d[[0, 0, 0], [0, 0, 0], [0, 0, 0]]>>> lst_2d[0][0] = 5>>> lst_2d[[5, 0, 0], [5, 0, 0], [5, 0, 0]]

The operator * duplicates its operands, and duplicated lists constructed with [] point to the same list. The correct way to do this is:

>>> lst_2d = [[0] * 3 for i in xrange(3)]>>> lst_2d[[0, 0, 0], [0, 0, 0], [0, 0, 0]]>>> lst_2d[0][0] = 5>>> lst_2d[[5, 0, 0], [0, 0, 0], [0, 0, 0]]


The only 'trick' I know that really wowed me when I learned it is enumerate. It allows you to have access to the indexes of the elements within a for loop.

>>> l = ['a','b','c','d','e','f']>>> for (index,value) in enumerate(l):...     print index, value... 0 a1 b2 c3 d4 e5 f