Simplest way of checking for string that contains a string in list?

PythonStringList

Python Problem Overview


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!'

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfredrikView Question on Stackoverflow
Solution 1 - PythonTerryAView Answer on Stackoverflow