Jason
Jason

Reputation: 4546

Remove a nested list if any of multiple values is found

I have a list of lists and I'd like to remove all nested lists which contain any of multiple values.

list_of_lists = [[1,2], [3,4], [5,6]]
indices = [i for i,val in enumerate(list_of_lists) if (1,6) in val]

print(indices)
[0]

I'd like a lists of indices where this conditions is so that I can:

del list_of_lists[indices]

To remove all nested lists which contain certain values. I'm guessing the problem is where I try to check against multiple values (1,6) as using either 1 or 6 works.

Upvotes: 1

Views: 62

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125248

You could use a set operation:

if not {1, 6}.isdisjoint(val)

A set is disjoint if none of the values appear in the other sequence or set:

>>> {1, 6}.isdisjoint([1, 2])
False
>>> {1, 6}.isdisjoint([3, 4])
True

Or just test both values:

if 1 in val or 6 in val

I'd not build a list of indices. Just rebuild the list and filter out anything you don't want in the new list:

list_of_lists[:] = [val for val in list_of_lists if {1, 6}.isdisjoint(val)]

By assigning to the [:] whole slice you replace all indices in list_of_lists, updating the list object in-place:

>>> list_of_lists = [[1, 2], [3, 4], [5, 6]]
>>> another_ref = list_of_lists
>>> list_of_lists[:] = [val for val in list_of_lists if {1, 6}.isdisjoint(val)]
>>> list_of_lists
[[3, 4]]
>>> another_ref
[[3, 4]]

See What is the difference between slice assignment that slices the whole list and direct assignment? for more detail on what assigning to a slice does.

Upvotes: 3

Related Questions