Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

List comprehensions in python

without comments

In the last post about Map-Filter-Reduce before finishing the post, I told about slight changes to those functions and how you can do the same job using list comprehensions. I would be talking about it here today.

Three years back Guido van Rossum, the BFDL made a blog post about the fate of reduce() in Python 3000. He stated that map and filter confusing to many people and that list comprehensions were simple to read and understand. Guido wanted reduce() to be totally removed from the language as there weren’t any good uses of it except + and *.

List Comprehensions
So, what is this list comprehensions that Guido was talking about. It is just a concise way to create lists from another list (just like map() and filter()). It is easy on the eyes and clearer to understand.

It consists of an expression followed by a for clause and more for/if clauses. The result of this is a list gotten by evaluating the expression in the context of the for and if clauses.

>>> words = ['FOO', 'BAR', 'BAZ']
>>> [word.lower() for word in words]
['foo', 'bar', 'baz']
>>> nums = [1,2,3,4]
>>> [(x, x*x) for x in nums]
[(1, 1), (2, 4), (3, 9), (4, 16)]

This looks just like the map function. Now just add an if clause after the for, and you get the filter equivalent.

>>> nums = [1,2,3,4,5,6]
>>> [i for i in nums if i%2 == 0]
[2, 4, 6]

List comprehensions are easier to understand by just reading it as words - create a list of is for every i in nums if i%2 is equal to 0. Also list comprehensions are faster than map and filter as it doesn’t have to make function calls.

So, even though Guido wanted all the four functions to be removed from the standard library, he has announced that lambda, map and filter would stay - with the latter two having small changes - returning iterators instead of a list. Unfortunately reduce() is moved over to functools module.

So my next post is going to be a small example of using list comprehensions to find the singular form of a word.

Written by cnu

July 26th, 2008 at 11:22 pm

Posted in Python

Tagged with

Leave a Reply