Tuesday, June 22, 2010

python: list comprehensions - examples

There are excellent examples from Guido's site, perfect for a quick review of "list comprehensions":


>>> vec = [ 2, 4, 6 ]
>>> [ 3*x for x in vec ]
[6, 12, 18]
>>> [ 3*x for x in vec if x > 3 ]
[12, 18]
>>> [ [x , " squared is " , x**2] for x in vec if x > 1 ]
[[2, ' squared is ', 4], [4, ' squared is ', 16], [6, ' squared is ', 36]]

>>> #tuple generation
...
>>> [ (x, x**3) for x in vec ]
[(2, 8), (4, 64), (6, 216)]

>>> #generate a list whose elements are teh values of pi, from 1 to 6 decimal places
...
>>> [ str( round(22/7.0 , i) ) for i in range(1,7) ]
['3.1', '3.14', '3.143', '3.1429', '3.14286', '3.142857']

No comments: