52

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!'
TerryA
  • 58,805
  • 11
  • 114
  • 143
fredrik
  • 9,631
  • 16
  • 72
  • 132
  • 8
    +1 for not just saying "Is there a simply way to ..." and actually showing what you had. Well done – TerryA Nov 01 '13 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 01 '13 at 13:01
  • 1
    Just curious, why do you keep needing this again and again? I can't think of a use case. – Christoffer Hammarström Nov 01 '13 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 01 '13 at 20:01

1 Answers1

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.

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 1
    +1 For plain and simple but still very useful answer. –  Nov 01 '13 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 http://docs.python.org/2/library/functions.html#any ) – Silverfish Nov 01 '13 at 17:45
  • @Haidro - Perfect! Many thanks. I need to read up on generator expressions, clearly. – fredrik Nov 02 '13 at 08:08
  • you should also avoid naming variables capitalized names like `L` as this goes against PEP8 :) – Neil G Nov 03 '13 at 08:56
  • @NeilG Actually, quoting the PEP8, it says `When tempted to use 'l', use 'L' instead.` - [link](http://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions) – TerryA Nov 03 '13 at 09:15
  • That's unfortunate because it also says that instance variables should be "lowercase with words separated by underscores as necessary to improve readability." – Neil G Nov 03 '13 at 11:10