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

Andrew Berg bahamutzero8825 at gmail.com
Mon Mar 18 02:24:30 CET 2013

On 2013.03.17 19:58, 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?
In the first example, sorted() returns a list, which is assigned to the
name tricky (Python doesn't have variables - names simply point to
objects in memory), and then the for loop iterates over tricky, which
points to a list. In the second example, the for loop iterates over the
list that sorted() returns. The only difference between the two is that
the list that sorted() returns is assigned to a name in the first example.

CPython 3.3.0 | Windows NT 6.2.9200 / FreeBSD 9.1

More information about the Python-list mailing list