Sunday, June 26, 2011

List Comprehensions



I have published a post regarding the functional programming tools in Python. I explained about map(), reduce(), filter() and lambda() in that post. 

There is also another way to create lists using conditions and that method is called as list comprehension. This method is more clearer than the map(),lambda() etc. Each list comprehension consists of an expression followed by a ‘for’ clause, then zero or more for or ‘if’ clauses. The result will be a list resulting from evaluating the expression in the context of the ‘for’ and ‘if’ clauses which follow it. If the expression would evaluate to a tuple, it must be parenthesized.

The syntax is [ expr for var in list ]

Sample code is given below,

nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ]
Output will be [1, 4, 9, 16]

Some more examples that can be experimented on interactive mode are given below.

>>> 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]
[(2, 4), (4, 16), (6, 36)]

We can also add the ‘if’ clause as given below.

fruits = ['apple', 'cherry', 'bannana', 'lemon']
afruits = [ s.upper() for s in fruits if 'a' in s ]
Output will be ['APPLE', 'BANNANA']

List comprehensions can be nested. They are a powerful tool, but like all powerful tools, they need to be used carefully, if at all.

Thanks

AJAY

No comments:

Post a Comment