# [Tutor] list comprehensions

wesley chun wescpy at gmail.com
Fri Oct 9 07:21:19 CEST 2009

```> I've been studying python now for a few weeks and I've recently come
> into 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.

that's pretty much correct.

> 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?

the "do something" can also include "do nothing!" in other words, you
can simply just select certain elements that meet your particular
criteria. for example, let's say you just want all the odd numbers
from 0 to 19:

odd = [x for x in range(20) if x % 2 != 0]

you just wanted the numbers but not to really do anything with them
other than have them as elements in a newly-created list.

your question also brought up "generator expressions" which are
lazier, more memory-friendly alternative to "listcomps." the syntax is
nearly identical, with the only difference being that they're enclosed
by parentheses instead of square brackets:

odd_gen = (x for x in range(20) if x % 2 != 0)

that's the only difference syntactically. however, there is a bigger
difference under the covers:

>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> odd_gen
<generator object <genexpr> at 0x012F44E0>

notice that memory is allocated and the entire list created in memory
for the listcomp but just a generic object for the "genexp." they are
"lazy" because you iterate over the values one at a time instead of
creating the entire list. they are slightly slower but save memory.
similar constructs for dicts and sets appear in Python 3: dictionary
and set comprehensions.

back to your question regarding sum(). sum() just iterates over the
genexp and adds up all the individual numbers iterated over.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
```