'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' in things
True
This works, but is there not a more Pythonic way of doing this check without having multiple or
statements? I can't find anything in the standard Python set operations that can achieve this. Using {'foo', 'bar'} <= things
checks for both, but I want to check for either of them.
Solution 1:[1]
As long as you're using sets, you could use:
if {'foo','bar'} & things:
...
&
indicates set intersection, and the intersection will be truthy whenever it is nonempty.
Solution 2:[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:[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:[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:[5]
things = {'foo', 'bar', 'baz'}
any([i in things for i in ['foo', 'bar']])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | RemcoGerlich |
Solution 3 | Thierry Lathuille |
Solution 4 | Aran-Fey |
Solution 5 | ComplicatedPhenomenon |