Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

for loop - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...