Unable to come up with reason for the given for loop (Python 3.11)

Question:

a=[1,2,3,4]
s=0

for a[-1] in a:
    print(a[-1])
    s+=a[-1]
print('sum=',s)

The output for the above code is

1
2
3
3
sum= 9

Could you explain why? A dry run would be appreciated.

I tried to come up with a dry run but I did not understand the output at all.

Asked By: 31 – Neil Mande

||

Answers:

Change code to next you can understand it clearly:

a=[1,2,3,4]
s=0

for a[-1] in a:
    print(a[-1])
    print(a)
    s+=a[-1]
print('sum=',s)

execution:

1
[1, 2, 3, 1]
2
[1, 2, 3, 2]
3
[1, 2, 3, 3]
3
[1, 2, 3, 3]
sum= 9

You could see with every loop, the last item of that list be updated with 1, 2, 3 (NOTE: list[-1] in python means last item of list), and when you loop it for the last time, the value is nolonger 4, but 3.

Answered By: atline

I try to explain it with an exmaple.

Assume this snippet:

for i in a:
    ...

In this code, in each iterate, i will be an element of a. It’s like: i=a[0], i=a[1], … .

Now when you have this code:

for a[-1] in a:
    ...

It’s like you are doing this in each iterate: a[-1] = a[0], a[-1] = a[1], a[-1] = a[2] and …

So you are changing last element each time, and when your iterate ends, your last element would be 3.

Answered By: Amin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.