Pythonic way to check for membership and get member

a_set = {'a', 'b', 'c'}
word = 'foobar'
for item in a_set:
  if item in word:
    print(item)

I’d like for the below code to do what the above code does

if any(item in lst for item in word):
  # print(item)

I like this syntax more because it’s easier to read. But is there a way to retrieve the item value that returned True in any()? Or is there another function for this?

Answer

You can use set.intersection, which also has the nice effect of O(1) membership testing* versus linearly O(N) scanning the string:

>>> a_set = {'a', 'b', 'c'}
>>> word = 'foobar'
>>> a_set.intersection(word)
{'a', 'b'}

*Specifically, calling a_set.intersection(word) will still require a once-over O(N) scan of word to convert it to a set internally. However, each check from then on is O(1) (for each member of a_set). You can contrast this to the snippet in your question, where each individual check is O(N).


The second part of your question is asking something slightly different, it seems; the equivalent of the any() call would be:

>>> if a_set.intersection(word):
...     # do something

where the condition will test True if the intersection contains 1 or more elements.

Leave a Reply

Your email address will not be published. Required fields are marked *