0

I was trying to delete some elements which contain specific substring of a list. For this reason, I tried to use the remove() to solve my problem.

However, remove() did not solve my problem and I even found out that the for-loop didn't loop through. Does any one have any idea? Based on the documentation from Python, I know remove() does only delete the occurrent element.

The following is my example code and its output:

l = ['x-1', 'x-2', 'x-3', 'x-4', 'x-5', 'x-6', 'x-7', 'x-8', 'x-9', 'x-10', 'x-11']
for i in l:
    print(i)
    if 'x-1' in i:
        l.remove(i)
        print('l after removed element: ', l)
print(l)

Output

x-1
l after removed element:  ['x-2', 'x-3', 'x-4', 'x-5', 'x-6', 'x-7', 'x-8', 'x-9', 'x-10', 'x-11']
x-3
x-4
x-5
x-6
x-7
x-8
x-9
x-10
l after removed element:  ['x-2', 'x-3', 'x-4', 'x-5', 'x-6', 'x-7', 'x-8', 'x-9', 'x-11']
['x-2', 'x-3', 'x-4', 'x-5', 'x-6', 'x-7', 'x-8', 'x-9', 'x-11']
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kai-Chun Lin
  • 185
  • 1
  • 2
  • 10
  • 1
    Sometimes a list comprehension is useful in this situation; `l = [i for i in l if 'x-1' not in i]` – bn_ln Jan 22 '23 at 10:38
  • I agrre, this is also a good approach but I just want to figure out how does remove() work. Thank you! – Kai-Chun Lin Jan 22 '23 at 10:40
  • `remove()` just removes an element. The problem is when doing it while iterating over the list. You remove an item and change the structure of the list. Now the iterator of the list "skips" an element because the elements "moved" unexpectedly – Tomerikoo Jan 22 '23 at 10:41

1 Answers1

1

The problem is that you're modifying the list while enumerating it. Manage your for loop by using a copy of the list as follows:

l = ['x-1', 'x-2', 'x-3', 'x-4', 'x-5', 'x-6', 'x-7', 'x-8', 'x-9', 'x-10', 'x-11']
for i in l[:]: # <--- here's the change
    print(i)
    if 'x-1' in i:
        l.remove(i)
        print('l after removed element: ', l)
print(l)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22