-4
a=[0,1,2,3]
for a[-1] in a :
    print a[-1]

This Program gives me an output 0 1 2 2

I am not able to decode it. I was expecting it to print the list in reverse direction. or at least print 3 alone. Can someone help me to understand this output

Soumya
  • 323
  • 1
  • 5
  • 16
  • 1
    reusing `a` to assign it back to itself isn't a good idea. use `for i in reversed(a): print i` – Jean-François Fabre Jun 26 '18 at 06:37
  • 1
    I think what you were _trying_ to write ia `for x in a[::-1]:`? If you're going to copy random code from unspecified places, you have to understand what it means, or at least copy it exactly. – abarnert Jun 26 '18 at 06:39
  • 1
    By writing `for a[-1] in a`, making `a[-1]` the loop variable, you're assigning each value in the array, in turn, to the last slot in the array. Hopefully it's clear why that's a bad idea. – jonrsharpe Jun 26 '18 at 06:40
  • possible duplicate of https://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python – Terry Jun 26 '18 at 06:41
  • I don't understand the code properly. Got it from internet. I was curious to know the output. I know how to reverse a string in python. I was seeking for a help in understanding the output for this specific question. What is actually happening in the list is what i wanted to know – Soumya Jun 26 '18 at 06:42

2 Answers2

2

at each iteration a[-1] (the last element of a) is assigned a value of a (the list becomes [0,1,2,0] then [0,1,2,1] then [0,1,2,2])

a=[0,1,2,3]
for a[-1] in a :
    print(a[-1])

It "works" until the end (although forward, not reversed), where the last iteration yields the last iterated upon value: 2

Now of course if you just want to iterate a list backwards:

for i in reversed(a):
   print(i)

reversed(a) is better than a[::-1] here because it doesn't create a list just to iterate on it.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

You can use

for x in a[::-1]:
    print x

Which goes "reads" the list in reverse order, one element at a time. A list is implicitly "read" like a[::1]. If you'd like to "read" a list in reverse order but every second element you could use a[::-2] which would give you [3, 1].

Or you can use

for x in reversed(a):
    print x
aydow
  • 3,673
  • 2
  • 23
  • 40