How iterable of list[index] over same list works

Viewed 57

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

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

Output:

1
2
3
40
40

Can anyone please help me understand what is going on behind the scene? I have some understanding of how interables works but this one is confusing me.

1 Answers

for item in list statement assigns each element in list to item in every iteration. When you type A[-1] instead item, it assigns element to A[-1], and A list changes.

To understand better let's change your for loop without affecting result and code logic, and add an extra print.

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

Output:

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]

As you see, in every iteration, last item of A changes. It overwrites the last element. At last iteration the one before the last item(40) becomes the last item.

Related