Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!'
like image 960
fredrik Avatar asked Nov 01 '13 12:11

fredrik


People also ask

How do you check if a string contains a substring in a list?

The easiest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ).


1 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.

like image 192
TerryA Avatar answered Oct 06 '22 11:10

TerryA