list comprehension

vatamane at gmail.com vatamane at gmail.com
Sat Jul 1 04:07:19 EDT 2006


I found the Wiki article on list comprehensions useful for
understanding the general concept.
See it at: http://en.wikipedia.org/wiki/List_comprehension
It talks about how a list comprehension can be thought of as equivalent
to a traditional set-builder notation in math. For example in math
notation, the expression S={x | x in N, x>4} creates an enumerable,
infinite set {5,6,7,...}.

In Python a similar concept applies. Say you have a list L1=[1,2,3,4,5]
and you need another list L2 that will contain the 10th power of all
the elements of  L1 greater than 3. In traditional math set notation
you  would write something like:
L2={x^10 | x in L1, x>3}
and in Python it would be:
L2=[x**10 for x in L1 if x>3]
You can see the correspondence between the two notations. The 'for' is
like '|' and ',' is like an 'if', in rest it is almost the same.

Hope this helps.
-Nick




Simon Forman wrote:
> a wrote:
> > can someone tell me how to use them
> > thanks
>
> basically, a list comprehension is just like a for loop,  if you wrote
> it out the "long way" it would be something like this:
>
> results = []
> for var in some_iterable:
>     if some condition:
>         results.append(some expression)
>
>
> The list comprehension version:
>
> results = [some expression for var in some_iterable if some condition]
>
>
> There's more to it, but that's the basic idea.
> 
> Hope this helps,
> ~Simon




More information about the Python-list mailing list