Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a list element exists in a string

Tags:

python

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!

like image 865
Homap Avatar asked Dec 18 '22 04:12

Homap


1 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.

like image 128
Martijn Pieters Avatar answered Dec 20 '22 20:12

Martijn Pieters