How does a list actually work in python using for-loop?

I tried this code, I do not 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
+4
source share
2 answers

Change the loop a bit:

a=[1,'a',2,'b','test','exam']
for temp in a:
    a[-1] = temp
    print(a[-1])

This loop does the same.

EDIT:

Here are all the 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 two iterations.

+4
source

In python, you can access the last element of a list implicitly using an index -1. So, it a[-1]will return the value of the last element of the list a.

By executing a for loop for a[-1] in a, you iterate over the list and store the value of the next element ain your last element.

, , , :

a=[1, 'a', 2, 'b', 'test', 'exam']
for a[-1] in a:
    print(a)

:

[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']

, , , 'exam', .

, .

+5

Source: https://habr.com/ru/post/1694180/


All Articles