'The copy of a list is not being iterated through all the elements

t=[1,2,3,5,2,1]
j=t.copy()

for f in j:
    print(f)
    j.remove(f)
    print(j)

Output

1
[2, 3, 5, 2, 1]
3
[2, 5, 2, 1]
2
[5, 2, 1]

I have a list t and I create a copy of it in j by calling t.copy().

But when I use the looping constructs, it does not traverse through all the elements. For example, in the output it selects 1, removes it and then prints the list without that element. After that it should choose 2 which is the next element and remove the same, but it selects 3 instead and 5 in the next iteration.

What could possibly be the reason for this alternate selection? Perhaps this is quite simple, but I am unable to figure the reason out.



Solution 1:[1]

The issue is that while you're iterating through the list you're also editing it leading to errors. Instead of iterating through j iterate through t since it'll remain the same throughout iterations.

Code:

t = [1, 2, 3, 5, 2, 1]
j = t.copy()

for f in t:
    print(f)
    j.remove(f)
    print(j)

Output:

1
[2, 3, 5, 2, 1]
2
[3, 5, 2, 1]
3
[5, 2, 1]
5
[2, 1]
2
[1]
1
[]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jawand S.