I tried this code, I don't understand how it works
a=[1,'a',2,'b','test','exam']
for a[-1] in a:
print(a[-1])
output
1
a
2
b
test
test
In python you can access the last element of a list implicitly by using the index -1
. So a[-1]
will return the value of the last element of the list a
.
By doing the for loop for a[-1] in a
, you iterate through the list, and store the value of the next element of a
in its last element.
So to better understand what's going on, you should print the whole list at every iteration, so you can visualize the operation:
a=[1, 'a', 2, 'b', 'test', 'exam']
for a[-1] in a:
print(a)
You will get:
[1, 'a', 2, 'b', 'test', 1]
[1, 'a', 2, 'b', 'test', 'a']
[1, 'a', 2, 'b', 'test', 2]
[1, 'a', 2, 'b', 'test', 'b']
[1, 'a', 2, 'b', 'test', 'test']
[1, 'a', 2, 'b', 'test', 'test']
You can see that at every iteration the last element will hold the value of the upcoming element, and actually you will lose the original content of the last element, i.e. 'exam'
as it's getting overwritten in every iteration.
Hope it makes sense now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With