user1728853
user1728853

Reputation: 2707

Delete an item from a list by match not index

I have a nested list that looks like this:

lst = [[1,2,3],["a","b","c"],[4,5,6]]

I would like to delete an item from this list by matching, not by index. For example, how can I delete [4, 5, 6]?

Upvotes: 3

Views: 116

Answers (2)

Jon Clements
Jon Clements

Reputation: 142136

If you wanted to remove multiple occurrences (lst.remove will only remove the first match), then it's generally easier to use a list-comp to recreate the list without the elements you want...

lst = [el for el in lst if el != [4,5,6]]

Upvotes: 2

arshajii
arshajii

Reputation: 129507

You could just use lst.remove(...):

lst = [[1,2,3],["a","b","c"],[4,5,6]]
lst.remove([4,5,6])
print lst

Output:

[[1, 2, 3], ['a', 'b', 'c']]

Upvotes: 2

Related Questions