(6)

PythonExamples

filter()

For example, you can filter all the empty strings out of the list:

>>> s = [‘one’, ”, ‘two’, ”, ”, ‘three’]
>>> filter(None, s)
[‘one’, ‘two’, ‘three’]

It also works for removing empty lists:

>>> s = [[1,2], [], [3,4,5], [], [], [6,7]]
>>> filter(None, s)
[[1,2], [3,4,5], [6,7]]

Plus, you can use the lambda-form to define your own filter criterion:

>>> s = [0, 1, 2, 3, 4, 5, 6]
>>> filter( (lambda(x) : x > 2.5), s )
[3, 4, 5, 6]

enumerate()

When used in a for construct, it gives you the index of each entry (like a C++ for-loop) in addition to the element itself.

>>> abc = [‘a’,‘b’,‘c’]
>>> for i,element in abc: print ’%d: %s’ % (i,element)
0: a
1: b
2: c