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

Gary Herron gary.herron at islandtraining.com
Sun Mar 17 21:18:12 EDT 2013


On 03/17/2013 05:58 PM, Yves S. Garret 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?

Just once.  The sorted fn is called just once, and the resulting list is 
iterated through.  In your first case, the list is bound to (assigned 
to) a name so it is accessible afterwards.  In the second case, it is 
available for garbage collection immediately after the loop finishes.

Gary Herron




More information about the Python-list mailing list