[Tutor] List comprehensions

Sean Perry shaleh at speakeasy.net
Wed Mar 23 18:35:53 CET 2005


Liam Clarke wrote:
> Is there any guides to this (possibly obtuse) tool?
> 

Think of it this way. A list comprehension generates a new list. So, you 
should think about list comps whenever you have old_list -> new_list 
style behavior.

There are two advantages to list comps over map:

1) a list comp can use a predicate to filter results

[ x for x in mylist if is Prime(x) ] for instance. that would be 
map(lambda x: x, filter(isPrime, mylist)) which is a little more dense.

2) usually there is no need for a lambda. Not that there is anything 
wrong with lambdas mind you (-:



More information about the Tutor mailing list