Bio-Python

"Ramblings on computational chemistry, in silico experiments and programming in python 3.x"

February 28, 2013

Python 3: Filter function and list comprehensions

Many of you who are familiar with python 2 and have switched to python 3 may already know that functions (filter, map, range etc.) that returned a list no longer do so. In python 3, these functions return an iterator.
In case you wish to use filter, map etc. and get a list in python 3, you have two techniques at your disposal, namely:
  1. Wrap the iterator around list( ) 
  2. Use list comprehensions instead

Wrapping the iterator around list

The following snippets returns all even numbers upto but not including 10.

Using list comprehension technique

We can modify the above program to do the same task but using more familiar list comprehension method.

This also gives us all even number upto but not including 10.

Leave a comment explaining how there two coding styles differ in efficiency and readability?