Python has a cleaner way to express "if x contains a | b | c | d ..."?

Pythonic way to check if string x substring of y :

 if x in y: 

Search if x equivalent to a , b , c , d , e , f or g also Pythonic:

 if x in [a,b,c,d,e,f,g]: 

But, if any row x contains either a , b , c , d , e , f , or g seems awkward:

 if a in x or b in x or c in x or d in x or e in x or f in x or g in x 

Is there a more Pythonic method for checking if row x contains a list item?

I know that it is trivial to write this myself, using a loop or using a regular expression:

 re.search('(dog|cat|bird|mouse|elephant|pig|cow)', x) 

but I was wondering if there is a cleaner way that is not related to regex.

+72
python substring if-statement
Oct 31 '13 at 18:29
source share
4 answers

Pythonic's approach would be to use any() :

 if any(s in x for s in (a,b,c,d,e,f,g)): 

From related documentation:

any (iteration)

Returns True if any iterability element is true. If iterability is empty, return False. Equivalent to:

 def any(iterable): for element in iterable: if element: return True return False 

Also note that I used a tuple instead of a list here. If your a - g values ​​are predefined, then a tuple will really be preferable. See: Are tuples more efficient than lists in Python?

+117
Oct 31 '13 at 18:32
source share
 if any(q in x for q in [a,b,c,d,e,f,g]): 

I think it is as short and pythonic as you can get it.

+26
Oct 31 '13 at 18:32
source share

A bit late for the party, but

 not frozenset(x).isdisjoint(frozenset(y)) 

will work and may be faster (algorithmically, but maybe not for smaller test cases).

+10
Nov 01. '13 at 5:25
source share

without using any , but just max

 def is_in(symbol, lst): return max([symbol in x for x in lst]) print is_in('a',['ae','br','tl']) print is_in('c',['ae','br','tl']) 

gives

 >>> True False 
+3
Nov 01 '13 at 4:05
source share



All Articles