[Python 2.7.3] What's the difference between these two uses of "for"?

Roy Smith roy at panix.com
Sun Mar 17 22:28:32 EDT 2013


In article <7f3b4dde-fbd7-44ca-96bc-31a6b2894200 at googlegroups.com>,
 "Yves S. Garret" <yoursurrogategod at gmail.com> wrote:

> I'm trying to better understand what's going on behind the scenes and I
> appreciate your thorough input.  What I don't understand is, how would you
> avoid creating L1?

Leave out the square brackets in:

sorted([w for w in set(text2) if 'cie' in w or 'cei' in w])

If you re-write that as:

sorted(w for w in set(text2) if 'cie' in w or 'cei' in w)

Now you've got what's called a generator expression.  This iterates over 
the same values as the list comprehension would, but it generates them 
one at a time, so it doesn't have to store them all somewhere.  It 
essentially a really neat syntax for writing coroutines.

As usual, Stack Overflow does a pretty good job explaining this:

http://stackoverflow.com/questions/47789/



More information about the Python-list mailing list