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

The following code fragments may work in this message.

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

Refer to this answer

By doing this for a[-1] in a, you actually iterate over the list and temporarily store the value of the current item in a[-1].

Similarly, I think that, while executing for a in a, it should iterate over the list and temporarily store the value of the current element in a, so the value amay 0and may not be iterable, then the Exception TypeErrorwill be selected in the next iteration. However, the result is as follows.

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

How to understand this?

+4
source share
1 answer

for,

expression_list. , , .

, , . , , , .

, for a in a:, - a, -. , a - , - . .

+3

Source: https://habr.com/ru/post/1623656/


All Articles