[Tutor] list comprehensions

Oxymoron moron.oxy at gmail.com
Fri Oct 9 07:17:44 CEST 2009


Hello,

On Wed, Oct 7, 2009 at 6:57 AM, Christer Edwards
<christer.edwards at gmail.com> wrote:
>
> do something to x for each x in list, with an optional qualifier.
>

To be more precise:

http://docs.python.org/tutorial/datastructures.html#list-comprehensions

"Each list comprehension consists of an expression followed by a for
clause, then zero or more for or if clauses"

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

So, it's not an 'action' as such, but an expression, x in this case is
a variable containing a number, thus stating 'x' by itself is an
expression that yields x's value and adds it to the sequence being
generated without doing anything else to it. The built-in function sum
(on the interpreter, type: help(sum)) takes a sequence of (numeric)
values and returns their... sum :-).

> In this case is sum() acting as the "action" on the first x? Can
> anyone shed some light on what it is I'm not quite grasping between
> the two?

Hence, sum does not know about x at all, just about the end result of
the generator expression: the generated sequence first evaluated, then
passed into it as an argument.

-- Kamal



--
There is more to life than increasing its speed.
-- Mahatma Gandhi


More information about the Tutor mailing list