[Tutor] list comprehensions

Gregor Lingl gregor.lingl at aon.at
Fri Oct 9 07:03:01 CEST 2009



Christer Edwards schrieb:
> I've been studying python now for a few weeks and I've recently come
> into list comprehensions. Some of the examples that I've found make
> sense, and I find them readable and concise. In particular I'm
> referring to the python docs on the topic
> (http://docs.python.org/tutorial/datastructures.html#list-comprehensions).
> Those make sense to me. The way I understand them is:
>
> do something to x for each x in list, with an optional qualifier.
>
> On the other hand I've seen a few examples that look similar, but
> there is no action done to the first x, which confuses me. An example:
>
> print sum(x for x in xrange(1,1000) if x%3==0 or x%5==0)
>
> In this case is sum() acting as the "action" on the first x?
No.

 >>> (x for x in xrange(1,100) if x%3==0 or x%5==0)
<generator object <genexpr> at 0x011C1990>

Is a generator expression. If you want to see what it generates, create 
e.g. a tuple

 >>> tuple(x for x in xrange(1,100) if x%3==0 or x%5==0)
(3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 
42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 
81, 84, 85, 87, 90, 93, 95, 96, 99)

So you see that the generator selects those integers that are divisible 
by 3 or 5

 >>> sum(x for x in xrange(1,100) if x%3==0 or x%5==0)
2318

This calculates the some of those.
There are quite a couple of functions in Python that accept generator 
expressions
as arguments

Regards,
Gregor

>   
>  Can
> anyone shed some light on what it is I'm not quite grasping between
> the two?
>
> Christer
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>   


More information about the Tutor mailing list