Check if a list element exists in a string

Viewed 1518

I'd like to check if a string contains an element from a list:

l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']

s = 'YTG'

The first solution is:

for i in l:
    if i in s:
        print i

This seems inefficient though. I tried the following code but it gives me the last element of the list 'M' instead of 'Y':

if any(i in s for i in l):
    print i

I was wondering what is the problem here?

Thanks!

3 Answers

any() produces True or False, and the generator expression variables are not available outside of the expression:

>>> l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']
>>> s = 'YTG'
>>> any(i in s for i in l)
True
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined

Use a list comprehension to list all matching letters:

matching = [i for i in l if i in s]
if matching:
    print matching

That preserves the order in l; if the order in matching doesn't matter, you could just use set intersections. I'd make l a set here:

l = set(['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M'])  # Python 3 can use {...}
matching = l.intersection(s)
if matching:
    print matching

By making l the set, Python can iterate over the shorter s string.

any will tell you if the condition is True or False, without giving more details.

To compute the actual common letters, just create a set and perform intersection:

l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']

s = set('YTG')
print(s.intersection(l))

that yields {'Y'}.

One liner:

set(list(s)).intersection(set(l))

{'Y'}

As per @Martijn Pieters♦ comment simply:

set(s).intersection(l) will do the trick, as shown in @Jean-François Fabre's answer

Related