53

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!'
4
  • 8
    +1 for not just saying "Is there a simply way to ..." and actually showing what you had. Well done
    – TerryA
    Nov 1, 2013 at 12:54
  • 5
    You don't need a local variable retVal in that function, just return True when you find it, else False. Skips some unnecessary loops. (and yes, just use any)
    – roippi
    Nov 1, 2013 at 13:01
  • 1
    Just curious, why do you keep needing this again and again? I can't think of a use case. Nov 1, 2013 at 17:26
  • 1
    Note that in python you can avoid using this kind of "flag variables". Put a break instead of the assignment and then use the else clause of the for loop to return False. In some cases this pattern can improve code readability and avoid too many indentation levels.
    – Bakuriu
    Nov 1, 2013 at 20:01

1 Answer 1

76

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.

6
  • 1
    +1 For plain and simple but still very useful answer.
    – user2742371
    Nov 1, 2013 at 12:55
  • 3
    any has the efficiency advantage equivalent to that given in @roippi's comment: it just returns true on the first instance of a true element, and false if it gets to the end without encountering a true element (check out the equivalent code docs.python.org/2/library/functions.html#any )
    – Silverfish
    Nov 1, 2013 at 17:45
  • @Haidro - Perfect! Many thanks. I need to read up on generator expressions, clearly.
    – fredrik
    Nov 2, 2013 at 8:08
  • you should also avoid naming variables capitalized names like L as this goes against PEP8 :)
    – Neil G
    Nov 3, 2013 at 8:56
  • @NeilG Actually, quoting the PEP8, it says When tempted to use 'l', use 'L' instead. - link
    – TerryA
    Nov 3, 2013 at 9:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.