Search code examples
pythonfor-loopif-statementany

Python: How to use if any("str" in item for item in list)?


The code snippet below returns an error that global name 'item' is not defined. How do I use if any(...) correctly to search for and print a string if found in a list?

def walk:
    list = ["abc", "some-dir", "another-dir", ".git", "some-other-dir"]
    if any (".git" in item for item in list):
        print item,

Solution

  • You don't. Don't use any() if you want to enumerate all the matching items. The name item only exists in the scope of the generator expression passed to any(), all you get back from the function is True or False. The items that matched are no longer available.

    Just loop directly over the list and test each in an if test:

    for item in lst:
        if ".git" in item:
            print item,
    

    or use a list comprehension, passing it to str.join() (this is faster than a generator expression in this specific case):

    print ' '.join([item for item in list if ".git" in item])
    

    or, using Python 3 syntax:

    from __future__ import print_function
    
    print(*(item for item in list if ".git" in item))
    

    If you wanted to find just the first such a match, you can use next():

    first_match = next(item for item in list if ".git" in item)
    

    Note that this raises StopIteration if there are no such matches, unless you give next() a default value instead:

    first_match = next((item for item in list if ".git" in item), None)
    if first_match is not None:
        print first_match,