Skip to content Skip to sidebar Skip to footer

Check For Any Values In Set

Suppose I have the following set: things = {'foo', 'bar', 'baz'} I would like to find out if either foo or bar exists in the set. I've tried: >>> 'foo' in things or 'bar'

Solution 1:

As long as you're using sets, you could use:

if {'foo','bar'} & things:
    ...

& indicates set indication, and the intersection will be truthy whenever it is nonempty.

Solution 2:

Talking sets, what you actually want to know is if the intersection is nonempty:

if things & {'foo', 'bar'}:
    # At least one of them is in

And there is always any():

any(t in things for t in ['foo', 'bar'])

Which is nice in case you have a long list of things to check. But for just two things, I prefer the simple or.

Solution 3:

You are looking for the intersection of the sets:

things = {'foo', 'bar', 'baz'}

things.intersection({'foo', 'other'})
# {'foo'}

things.intersection('none', 'here')
#set

So, as empty sets are falsy in boolean context, you can do:

if things.intersection({'foo', 'other'}):
    print("some common value")
else:
    print('no one here')

Solution 4:

You can use set.isdisjoint:

if not things.isdisjoint({'foo', 'bar'}):
    ...

Or set.intersection:

if things.intersection({'foo', 'bar'}):
    ...

Or any:

if any(thing in things for thing in ['foo', 'bar']):
    ...

Or stick with or, because very often that's actually the most readable solution:

if'foo'in things or 'bar'in things:
    ...

Solution 5:

things = {'foo', 'bar', 'baz'}
any([i in things for i in ['foo', 'bar']])

Post a Comment for "Check For Any Values In Set"