Reputation: 834
As I was going through some questions and answers recently, I've found a question:
x = [0, 1, 2, 3]
for x[-1] in x:
print(x[-1])
And the result was:
0
1
2
2
I was not satisfied with the answer description, the answer description says:
The value of x[-1] changes in each iteration.
Upvotes: 0
Views: 347
Reputation: 5065
When you write :
for a in x:
What happens is that you are assigning the elements in x to a in every iteration. So a
goes from 0
to 3
.
Now, when you do:
for x[-1] in x:
What you are doing is that you are assigning the last element of x
with a value in x
. This should clarify it:
>>> x = [0, 1, 2, 3]
>>> for x[-1] in x:
... print(x,x[-1])
#output
[0, 1, 2, 0] 0 # a = 0, make x[-1] = a, x becomes [0, 1, 2, 0], print x[-1] = 0
[0, 1, 2, 1] 1 # a = 1, make x[-1] = a, x becomes [0, 1, 2, 1], print x[-1] = 1
[0, 1, 2, 2] 2 # a = 2, make x[-1] = a, x becomes [0, 1, 2, 2], print x[-1] = 2
[0, 1, 2, 2] 2 # a = 2, make x[-1] = a, x becomes [0, 1, 2, 2], print x[-1] = 2
Explanation:
Here in the first iteration, a = 0
which is assigned to x[-1] so x
becomes [0, 1, 2, 0]
then you print x[-1]
which comes out to be 0
.
Then in the second iteration, a = 1
which is assigned to x[-1]
so x
becomes [0, 1, 2, 1]
then you print x[-1]
which comes out to be 1
.
And so on...
Upvotes: 3
Reputation: 101
The explanation is fated to be clear.
x[-1]
points to the last element of x
.
for x[-1] in x:
simply says: Iterate over elements in x
and save the current value to x[-1]
So here is the sequence whats going on on every iteration:
(before the start of the loop) x == [0, 1, 2, 3]
x[-1] = 0 # x == [0, 1, 2, 0]
x[-1] = 1 # x == [0, 1, 2, 1]
x[-1] = 2 # x == [0, 1, 2, 2]
x[-1] = 2 # x == [0, 1, 2, 2]
Upvotes: 3
Reputation: 12493
It's a nice question. To figure out what's going on, I expanded the code to:
x = [0, 1, 2, 3]
for x[-1] in x:
print(f"the array x is {x}")
print(f"the value of is x[-1] is {x[-1]}")
print("***") # just a separator between iterations
The result is
the array x is [0, 1, 2, 0]
the value of is x[-1] is 0
***
the array x is [0, 1, 2, 1]
the value of is x[-1] is 1
***
the array x is [0, 1, 2, 2]
the value of is x[-1] is 2
***
the array x is [0, 1, 2, 2]
the value of is x[-1] is 2
***
As you can see, python uses the last cell of the array - x[-1]
as the variable that holds the values it's iterating over. That's why, when we get to the last iteration, it holds the value '2' from the previous iteration, and that what it prints.
Upvotes: 3