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

Yves S. Garret yoursurrogategod at gmail.com
Sun Mar 17 22:01:50 EDT 2013


On Sunday, March 17, 2013 9:28:56 PM UTC-4, Roy Smith wrote:
> In article <485a3093... at googlegroups.com>,
> 
>  "Yves S. Garret" <your... at gmail.com> wrote:
> 
> 
> 
> > N00b question.  But here is the code:
> 
> > 
> 
> > http://bin.cakephp.org/view/709201806
> 
> > 
> 
> > 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 
> 
> mean:
> 
> 
> 
> [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:
> 
>    print word,
> 
> 
> 
> 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.

Hi, thanks for the detailed explanation.  And yes, you've answered my question.

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?



More information about the Python-list mailing list