Reputation:
In the mentioned code I expect output as 0 1 2 3
, but I got an output which is 0 1 2 2
.Please help me why it is so? , how it is working.This is the code of my problem statement.
a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
This is code in python, output got is 0 1 2 2
Upvotes: 1
Views: 170
Reputation: 3988
What you're doing is this:
>>> for i in a:
... a[-1] = i
... print(a[-1])
...
0
1
2
2
Its because a[-1] is assigned the value of next(iterable a) in a sense, at each loop.
for
loop makes iterable, then calls next on that iterable, then it's assigned to the iteration variable.
Upvotes: 1
Reputation: 922
In this case you are reassigning the values inside your list whilst iterating over it. If you print out the entire list in your loop you will see the following:
>>> for a[-1] in a:
... print(a)
...
[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]
If you want to go through individual items in your list you would have to name your variable a different way such as:
for item in a:
print(item)
Output then is 0 1 2 3
as you would expect.
Upvotes: 4