Use remove() function to delete elements containg specific substring from list

Question:

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']
Asked By: Kai-Chun Lin

||

Answers:

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)
Answered By: Pingu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.