Reputation: 561
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?
Upvotes: 2
Views: 156
Reputation: 231595
In [85]: a_set = {'a', 'b', 'c'}
...: word = 'foobar'
In [86]: [item for item in a_set if item in word]
Out[86]: ['b', 'a']
is the list comprehension equivalent of your first loop.
What are you trying to do with the second loop. Seems you've switched the string and list. The expression isn't any clearer to me.
Upvotes: 0
Reputation: 40918
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.
Upvotes: 3