Check for any values in set

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.


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.


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')

Tags:

Python

Set