How the list index fighter works on the same list

Suppose I have a list 'A' and I want to iterate over this list with A [-1]

A = [1,2,3,40,50]
for A[-1] in A:
    print(A[-1])

Conclusion:

1
2
3
40
40

Can someone help me understand what is going on behind the scenes? I have some understanding of how interfaces work, but it scares me.

+4
source share
1 answer
Operator

for item in listassigns to each element from listto itemevery iteration. When you enter A[-1]instead item, it assigns the item A[-1]and Achanges the list.

, for loop, , print.

A = [1,2,3,40,50]
for x in A:
    A[-1] = x
    print(A[-1])
    print(A)

:

1
[1, 2, 3, 40, 1]
2
[1, 2, 3, 40, 2]
3
[1, 2, 3, 40, 3]
40
[1, 2, 3, 40, 40]
40
[1, 2, 3, 40, 40]

, A . . (40) .

+3

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


All Articles