Saturday, June 25, 2011

List comprehensions

Python supports a concept called "list comprehensions". It can be used to construct lists in a very easy way.

In mathematics we can describe lists this way:

S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)
M = {x | x in S and x even}

In Python we can do this as::

>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]

Let's see the result:

>>> print S
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
print V
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
>>>
print M
[0, 4, 16, 36, 64]

More examples:
>>> [(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
any type of elements, including strings, nested lists and functions. We can even mix different types within a list.

list comprehensions work for any type of elements

>>> words='You can nest list comprehensions inside of each other'.split()
>>> words
['You', 'can', 'nest', 'list', 'comprehensions', 'inside', 'of', 'each', 'other']
>>> new=[[w.upper(), w.lower(), len(w)] for w in words]
>>> for i in new:
... print i
...
['YOU', 'you', 3]
['CAN', 'can', 3]
['NEST', 'nest', 4]
['LIST', 'list', 4]
['COMPREHENSIONS', 'comprehensions', 14]
['INSIDE', 'inside', 6]
['OF', 'of', 2]
['EACH', 'each', 4]
['OTHER', 'other', 5]
>>>



No comments:

Post a Comment