Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for any values in set

Tags:

python

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.

like image 222
Daniel Holmes Avatar asked Aug 30 '19 08:08

Daniel Holmes


2 Answers

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.

like image 161
khelwood Avatar answered Sep 21 '22 22:09

khelwood


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.

like image 22
RemcoGerlich Avatar answered Sep 21 '22 22:09

RemcoGerlich