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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With