Python Introducing Lists Using Lists Mutability

Akanksha Singh
Akanksha Singh
5,081 Points

Why doesn't list.remove() removes all the elements after using a for in loop, but using loop in for list.copy() does?

#code for review - aim to remove all the elements from the list
l = [1,2,3,4,5,6]

#removed one element
l.remove(2)
#looping through list and removing element
for num in l:
     l.remove(num)
#expected an empty list but instead got two items that too not the last two
print (l)

#if I use l.copy() in the loop then it works
for num in l.copy():
     l.remove(num)
#got an empty list
print(l)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,649 Points

Modifying the loop iterable shifts the items relative to their indexes:

#code for review - aim to remove all the elements from the list
l = [1,2,3,4,5,6]

#removed one element
l.remove(2)
#looping through list and removing element
for idx, num in enumerate(l):
     l.remove(num)
     print('loop 1:', l, idx, num)
#expected an empty list but instead got two items that too not the last two
print ('result 1:', l)

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

#if I use l.copy() in the loop then it works
for idx, num in enumerate(l.copy()):
     l.remove(num)
     print('loop 2:', l, idx, num)
#got an empty list
print('result 2:', l)

Produces

loop 1: [3, 4, 5, 6] 0 1
loop 1: [3, 5, 6] 1 4
loop 1: [3, 5] 2 6
result 1: [3, 5]
loop 2: [2, 3, 4, 5, 6] 0 1
loop 2: [3, 4, 5, 6] 1 2
loop 2: [4, 5, 6] 2 3
loop 2: [5, 6] 3 4
loop 2: [6] 4 5
loop 2: [] 5 6
result 2: []