+ 1
Can you explain the output?
I found this code while doing a quiz and the output doesn't make any sense, can anyone explain it to me plz: a = [0, 1, 2, 3] for a[-1] in a: print(a[-1]) Output : 0 1 2 2
9 Respostas
+ 8
a[-1] will become an iterator, and it will change in every loop, by the value in a:
1st loop: a[-1] = 0; a = [0, 1, 2, 0]
2nd loop: a[-1] = 1; a = [0, 1, 2, 1]
3rd loop: a[-1] = 2; a = [0, 1, 2, 2]
In the 4th loop it will take the last value of a, which is a[-1] itself, so same output again:
4th loop: a[-1] = 2; a = [0, 1, 2, 2]
+ 4
med gazzeh yes, it assigns to itself the valies of a. Since it is already in a, there will be a point where it reaches itself, so it will take the same value twice in a row.
If for example you looped throught:
for a[-1] in range(100):
pass
a[-1] will take the last value it was, which is 99 in this case.
+ 4
med gazzeh No problem
+ 3
med gazzeh you can consider a as a variable.
When you use a for loop, it is like saying every time, put i = 1, i = 2, i = 3, i = 4... think of it as changing the variable name.
After every for loop, the iterator used does not actually disappear, but it is created as a variable. Say we have this program:
for i in range(10):
pass
print(i) # output: 9
Same goes to a[-1], it is like writing:
a[-1] = 0
a[-1] = 1
...
+ 2
Aymane Boukrouh [INACTIVE]
Thanks of the quick answer :)
+ 2
Aymane Boukrouh [INACTIVE]
ok, I got it, thanks :D
+ 2
Aymane Boukrouh [INACTIVE]
I already knew that but the fact that the element a[-1] can be used to iterate through 'a' seemed very strange to me at first, but after your very first comment I came to realize that a[-1] is a variable in itself (feel free to correct me if I am wrong) all became clear. So thanks again :)
Ps : Sorry for late response
+ 1
Aymane Boukrouh [INACTIVE]
So a[-1] iterates through a and reassigns it's current value to itself?
+ 1
Aymane Boukrouh [INACTIVE]
It just struck me, I kept thinking how weard is this behaviour however if you think of a[-1] in terms of the allocated memory then it makes much more sense as the values in 'a' will just cycle through that part of memory (refered to by a[-1]) until it reachs it's own.