The easiest way to check a string containing a string in a list?

I find myself many times, I write the same piece of code:

def stringInList(str, list): retVal = False for item in list: if str in item: retVal = True return retVal 

Is there a way to write this function faster / with less code? I usually use this in an if statement, for example:

 if stringInList(str, list): print 'string was found!' 
+52
python string list
Nov 01 '13 at
source share
1 answer

Yes, use any() :

 if any(s in item for item in L): print 'string was found!' 

As mentioned in the docs, this is pretty much equivalent to your function, but any() can accept generator expressions instead of strings and list and any() short circuits. As soon as s in item is True, the function is interrupted (you can simply do this with your function if you just change retVal = True to return True ). Remember that functions break when they return a value).




You should avoid naming str strings and listing list . This will override the built-in types.

+77
Nov 01 '13 at
source share



All Articles