Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'for a[-1] in a' and 'for a in a' in Python?

In this post, the following code snippets could work.

a = [0, 1, 2, 3]
for a[-1] in a:
    print(a[-1])

Refer to this answer

While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into a[-1].

Likewise, I think doing for a in a, it should iterate through the list and temporary store the value of current element to a, so the value of a could be 0, and is not iterable, then TypeError exception will be thrown in the next iteration. However, the result is as below.

>>> a = [0, 1, 2, 3]
>>> for a in a:
...     print a
... 
0
1
2
3
>>> a
3

How to understand it?

like image 407
zangw Avatar asked Jan 10 '16 14:01

zangw


1 Answers

Quoting the official documentation on for loop,

An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices.

So, when you are iterating an object, an iterator object is created and that is used for iteration. That is why the original object is not lost, at least till the loop runs.

In your case, when for a in a: is executed, an iterator object is created for a first, and the values are retrieved from the iterator object. Even though the loop binds the name a to some other value on each iteration, the iterator object still holds reference to the original list object and it gives out values from it. That is why you are not getting any error.

like image 127
thefourtheye Avatar answered Oct 07 '22 05:10

thefourtheye