Simplest way of checking for string that contains a string in list?
Question:
I find myself repeatedly writing the same chunk of code:
def stringInList(str, list):
retVal = False
for item in list:
if str in item:
retVal = True
return retVal
Is there any way I can write this function quicker/with less code?
I usually use this in an if statement, like this:
if stringInList(str, list):
print 'string was found!'
Answers:
Yes, use any()
:
if any(s in item for item in L):
print 'string was found!'
As the docs mention, this is pretty much equivalent to your function, but any()
can take generator expressions instead of just a string and a list, and any()
short-circuits. Once s in item
is True, the function breaks (you can simply do this with your function if you just change retVal = True
to return True
. Remember that functions break when it returns a value).
You should avoid naming strings str
and lists list
. That will override the built-in types.
I find myself repeatedly writing the same chunk of code:
def stringInList(str, list):
retVal = False
for item in list:
if str in item:
retVal = True
return retVal
Is there any way I can write this function quicker/with less code?
I usually use this in an if statement, like this:
if stringInList(str, list):
print 'string was found!'
Yes, use any()
:
if any(s in item for item in L):
print 'string was found!'
As the docs mention, this is pretty much equivalent to your function, but any()
can take generator expressions instead of just a string and a list, and any()
short-circuits. Once s in item
is True, the function breaks (you can simply do this with your function if you just change retVal = True
to return True
. Remember that functions break when it returns a value).
You should avoid naming strings str
and lists list
. That will override the built-in types.