Liz Liz - 2 months ago 9
Python Question

Remove a tuple from a list if the tuple contains a certain element

I have a list of tuples (num, id):

l = [(1000, 1), (2000, 2), (5000, 3)]


The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of
2
, how do I do that?

I.e. I want the new list to be:
l = [(1000,1), (5000, 3)]


I have tried
l.remove(2)
but it won't work =[

Answer

You can use a list comprehension with a filter to achieve this.

l = [(1000, 1), (2000, 2), (5000, 3)]
m = [(val, key) for (val, key) in l if key != 2]
Comments