Liz Liz - 1 year ago 70
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
, how do I do that?

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

I have tried
but it won't work =[

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download