2
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.

atline
  • 28,355
  • 16
  • 77
  • 113
  • 1
    You're using a list index as a *loop variable*, so the value of each element in `a` will be written to `a[-1]` (i.e. the last index of the list). The code is therefore equivalent to `for v in a: a[len(a) - 1] = v`. – ekhumoro Jan 07 '23 at 14:08
  • Does this answer your question? [Why can I use a list index as an indexing variable in a for loop?](https://stackoverflow.com/questions/55644201/why-can-i-use-a-list-index-as-an-indexing-variable-in-a-for-loop) – ekhumoro Jan 07 '23 at 14:10

2 Answers2

2

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.

atline
  • 28,355
  • 16
  • 77
  • 113
2

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.

Amin
  • 2,605
  • 2
  • 7
  • 15