West
West

Reputation: 2570

How to remove members of a list in python

I have the following code to remove from the data list all sublists for which nums is a subset.and I dont understand why its not working:

data=[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
nums=[1,2]

for each in data:
    if set(nums).issubset(each):
        data.remove(each)

print(data)
>>[[1, 2, 4], [1, 3, 4], [2, 3, 4]]

Why isn't [1,2,4] being removed when nums is a subset of it, as seen below?

set(nums).issubset([1,2,4])
>>True

Upvotes: 0

Views: 321

Answers (3)

raul.vila
raul.vila

Reputation: 1984

You're modifing the list you're iterating from.

This is a nicer solution:

data=[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
nums=[1,2]

data = [each for each in data if not set(nums).issubset(each)]
print(data)

For learning purposes, see this code which also works. The difference with your code is that here we're not modifying data list in the for loop.

data=[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
nums=[1,2]

new_data = []
for each in data:
    if not set(nums).issubset(each):
        new_data.append(each)

data = new_data
print(data)

Upvotes: 10

Jacques Gaudin
Jacques Gaudin

Reputation: 16978

For your information, there is also a filterfalse function in the very useful itertools module.

from itertools import filterfalse

data = list(filterfalse(set(nums).issubset, data))

Upvotes: 2

Gianluca Micchi
Gianluca Micchi

Reputation: 1653

Because the iterator is unaware that you removed an element. When it passes to the second element, it finds [1, 3, 4] meaning that you skipped [1, 2, 4].

Upvotes: 2

Related Questions