Monday 4 July 2011

List comprehensions

    Python supports a concept called 'list comprehensions'. It can be used to construct lists in a very natural and easy way. The following are common ways to describe lists (or sets,or tuples, or vectors) in mathematics
     S = {: x in {0...9}}
     V = (1,2,4,8,...,2¹²)
    M = {x | x in S and x even }
In python we can written  it 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]
Output
>>> print S; print V; print M
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
[0, 4, 16, 36, 64]

Examples

>>> vec=[2,4,6]
>>> [3*x for x in vec]
[6, 12, 18]

>>> [3*x for x in vec if x>3]
[12, 18]

>>> [3*x for x in vec if x<2]
[]

>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]

>>> [x,x**2 for x in vec] # error - need () for tuples
File "<stdin>", line 1
[x,x**2 for x in vec]
^
SyntaxError: invalid syntax

>>> [(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]

List comprehensions are more flexible than map() and can be applied to complex expressions and nested functions.
Example
>>> [str(round(355/113.0,i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

In list comprehension list contain any type of elements including strings, nested lists and functions

Example
>>> words='The quick brown fox jumps over the lazy dog'.split()
>>> print words
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>>
>>> stuff=[[w.upper(),w.lower(),len(w)] for w in words]
>>> for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]
>>>
>>> stuff=map(lambda w: [w.upper(),w.lower(),len(w)],words)
>>> for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

This example shows that, we can do the same thing by using the map() and lambda function. But in most cases we use the list comprehension, because it is more efficient and easier to read.

No comments:

Post a Comment