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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With