Can someone please explain the following Python code?
a = [1, 2, 3, 4]
for a[-1] in a:
print(a)
And after execution, I am getting the following result but I am unable to understand the whole logic behind it.
Result
[1, 2, 3, 1]
[1, 2, 3, 2]
[1, 2, 3, 3]
[1, 2, 3, 3]
2 Answers 2
This loop will visit each slot of the list and put its value in a[-1]
, which is the last slot of the list. In this case a[-1]
is a reference to the same slot as a[3]
.
So we can unwrap the loop to this:
a = [1, 2, 3, 4]
a[3] = a[0] # First iteration
print(a)
a[3] = a[1] # Second iteration
print(a)
a[3] = a[2] # Third iteration
print(a)
a[3] = a[3] # Last iteration. Nothing changes here
print(a)
3 Comments
for (a[a.length-1] of a) console.log(a);
. Same effect.Basically in each iteration, the index position value is replaced in list. Let me run through a simple example first then to your question.
Example:
a = [1, 2, 3, 4]
for a[0] in a:
print(a[0])
print(a) # It replaces the first position a[0] with each iteration a[0, 1, 2, 3]
Output:
1 => (iteration 1, a[0]=1, replaced with 1 in a[0] position)
[1, 2, 3, 4]
2 => (iteration 2, a[0]=2, replaced with 2 in a[0] position)
[2, 2, 3, 4]
3 => (iteration 3, a[0]=3, replaced with 3 in a[0] position)
[3, 2, 3, 4]
4
[4, 2, 3, 4] => (iteration 4, a[0]=4, replaced with 4 in a[0] position)
Explanation on your Query:
a = [1, 2, 3, 4]
for a[-1] in a:
print(a[-1])
print(a) # It replaces the last position a[-1] with each iteration a[0, 1 ,2, 3]
Output:
1 => (iteration 1, a[-1]=1, replaced with 1 in a[-1] position)
[1, 2, 3, 1]
2 => (iteration 2, a[-1]=2, replaced with 2 in a[-1] position)
[1, 2, 3, 2]
3 => (iteration 3, a[-1]=3, replaced with 3 in a[-1] position)
[1, 2, 3, 3]
3 => (iteration 4, a[-1]=3 (as the position is already
[1, 2, 3, 3] replaced with 3. So, placed with 3 in a[-1] position))
1 Comment
3
instead original 4
on the last element was confusing before you explained it.
a[-1]
is the last value in the array so you are assigning every value in the array to the last value 1 by 1. However, you never get to 4 since 4 has been overwritten before you iterate that far.