[Python 2.7.3] What's the difference between these two uses of "for"?
roy at panix.com
Mon Mar 18 02:28:56 CET 2013
In article <485a3093-8c07-4d1a-b49e-af32f84f8198 at googlegroups.com>,
"Yves S. Garret" <yoursurrogategod at gmail.com> wrote:
> N00b question. But here is the code:
> In the first example, the first for-loop is run and then the list is assigned
> to the tricky variable. But, what
> happens in the second example? Does the loop after "in" get run only once or
> multiple number of times?
It's a little hard to answer your question because you're not using the
right terminology. When you say, 'the loop after "in"', I assume you
[w for w in set(text2) if 'cie' in w or 'cei' in w]
yes? That's not what most people would call "a loop". It's a list
comprehension. For sure, there's an implied looping over the elements
of set(text2) in there, but that's not the way people refer to it.
Anyway, here's what happens. Working from the inside out...
First, set(text2) is evaluated. I assume text2 is something like a list
of strings, or at least iterable which yields strings. This results in
a set object being created. Let's call that set S.
Next, the list comprehension gets evaluated:
[w for w in s if 'cie' in w or 'cei' in w]
This iterates over the the elements of s and forms a list out of those
elements which pass the condition in the 'if' clause. This results in a
list object being created. Let's call that L1
Next, sorted(L1) is evaluated. This returns another list (call it L2).
Finally, we get to:
for word in L2:
This iterates over all the elements in L2, assigning each one, in turn
to word, and executing the body of the for statement.
Does that answer your question? I'm sure other people will point out
that this is not the most efficient way to do this (your way is not
wrong, it's just not the most efficient way). There's a way to write
this which avoids creating L1. That could be important if there's a
large amount of data involved.
But, make sure you fully understand what's happing in the example you
gave before you move on to the next step.
More information about the Python-list