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