user3030969
user3030969

Reputation: 1575

How to check for a value in a list of tuples?

I have a list of tuples like this:

l = [(10,'bat'), (50,'ball'), (100,'goal')]

and I want to check if 100 is in any of the tuples. And if it is there I need to remove its value which is 'goal'.

How can I do this?

TIA

Upvotes: 0

Views: 163

Answers (2)

Umair Khan
Umair Khan

Reputation: 199

Checks for 100 in any column and removes 100 from tuple.

l = [(10,'bat'), (50,'ball'), (100,'goal')]
for i, row in enumerate(l[:]):
    if any(col == 100 for col in row):
        new_row = filter(lambda col: col != 100, row)
        l[i] = new_row

print l

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816322

You can use list comprehension to filter out the tuple:

l = [t for t in l if t[0] != 100]

If you want/have to do this with multiple values, you can create a set of them:

exclude = set(100, 30, 20)
l = [t for t in l if t[0] not in exclude]

Upvotes: 4

Related Questions