For variable types for traversal

For variable types for traversal

for example

lis = [1,6,1, 2, 3,3, 4, 5]
for i in lis:
    lis.remove(i)
    print(lis)

[6, 1, 2, 3, 3, 4, 5]
[6, 2, 3, 3, 4, 5]
[6, 2, 3, 4, 5]
[6, 2, 3, 5]

As a general idea, the result will be each print will be one less, to know the list [] so far.

Why would print such a result, because the list is a variable type, each change of its content is original address, the result of the next cycle of the list gradually become less, until i get any value.

Solution (copy of the list of new objects, used to traverse)

lis = [1,6,1, 2, 3,3, 4, 5]
for i in lis.copy():
    lis.remove(i)
    print(lis)

[6, 1, 2, 3, 3, 4, 5]
[1, 2, 3, 3, 4, 5]
[2, 3, 3, 4, 5]
[3, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]

Guess you like

Origin www.cnblogs.com/zx125/p/11305589.html