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.
Let's change the loop a little:
a=[1,'a',2,'b','test','exam']
for temp in a:
a[-1] = temp
print(a[-1])
This loop does the same.
All iterations:
temp = a[0] => a[-1] is 1 and a is [1,'a',2,'b','test',1]
temp = a[1] => a[-1] is 'a' and a is [1,'a',2,'b','test','a']
temp = a[2] => a[-1] is 2 and a is [1,'a',2,'b','test',2]
temp = a[3] => a[-1] is 'b' and a is [1,'a',2,'b','test','b']
temp = a[4] => a[-1] is 'test' and a is [1,'a',2,'b','test','test']
temp = a[5] => a[-1] is 'test' and a is [1,'a',2,'b','test','test']
Focus on the last 2 iterations.
Clobbering. for a[-1] in a sets a[-1] = a[1] because of the for loop. In the subsequent iterations, it does that again, so the contents of the list cycle. When it does the 6th iteration, you might be expecting the print to be "exam." However, remember what happened in the first iteration. a[-1] = a[1]. The exam string no longer exists, because it was clobbered by the integer 1. At that time, both a[1] AND a[-1] are the integer 1.
After the for loop completes, you exit its scope. In the main program's scope, the contents of the list a never changed. So your print at the end is irrelevant to what happened in the loop.
The for loop accepts all the same assignment targets a regular assignment does, no matter how silly. So it's assigning to the last position of the list repeatedly.
You really shouldn't use any indexing between for ... in. You should just write a variable name there, and don't write the name of any existing variable. No one would write code like this in a real project because for loops are not supposed to be used like this.
ato store the loop variable. Very weird if you ask me. Soexamis lost forever since the first iteration.