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

for a[-1] in a:

    print(a[-1])

I'm new to python, so can anyone explain the output of this code.

Output

0 1 2 2

a[-1] indicates the last element 3, so shouldn't the output be 3 3 3 3 ?

Mohd
  • 5,523
  • 7
  • 19
  • 30
trim24
  • 249
  • 3
  • 12
  • @Kshitij Grag Gave a good explanation, but I just want to note this is very convoluted and is hard to understand, you probably meant to declare a new variable as the iterator (e.g. for x in a). – nico Jun 27 '17 at 03:19
  • 2
    This code looks horrible, where ever you got that from, you should look somewhere else. – mwil.me Jun 27 '17 at 03:22

3 Answers3

2

What happens is that a[-1] is being used as the variable in which each element is being stored. So for a[-1] in a: iterates over each element in a and stores the value in a[-1] i.e a[3]

As the last value being stored in a[3] is a[2] i.e 2 ... The output is 0,1,2,2 Hope it is clear now.

Kshitij Garg
  • 35
  • 1
  • 11
0

This code is equivalent tu the following: a = [0, 1, 2, 3]

for x in a:

a[-1] = x

print(a[-1])

so a[-1] is changing

0

This code should help clarify:

a = [0, 1, 2, 3]

for a[-1] in a:

    print(a)

which outputs:

[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]

So what is happening is each time you go past the loop the list type is iterated upon starting at the start of your iterator (a), which brings the next item of the list into memory at the name you declared (a[-1]). Because you are changing the same thing you're iterating through, you get your unexpected result. Focusing on the last two outputs you can see that you write 2 into a[-1] and then iterate so you're looking at a[4] (which is also a[-1] in this case) but that was just rewritten to 2, hence your output.

What you probably wanted was something like:

a = [0, 1, 2, 3]

for foo in a:

    print(foo)
Gavin Achtemeier
  • 325
  • 2
  • 11