3

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,
  • You don't. Don't use `any()` if you want to enumerate all the matching items. – Martijn Pieters Feb 11 '18 at 00:21
  • Also, `item` will only exist within scope of your `any` method call. This is also why you are getting that error message for `item` not being defined. – idjaw Feb 11 '18 at 00:22
  • @MartijnPieters Do you mean to suggest that I use 'all' instead? What if I just wanted to find any one instance? Would the use of 'any' be a valid use case in that instance? – Siddharth Patil Feb 11 '18 at 00:25
  • @idjaw yes that makes sense to me, so how would I fix it though? By defining item as a global? – Siddharth Patil Feb 11 '18 at 00:27
  • @SiddharthPatil Look at the answer that was provided. All the information is there for you and very well explained. – idjaw Feb 11 '18 at 00:28
  • @SiddharthPatil: no, `any()` always returns true, or false, nothing else. Use `next()` on a generator instead. – Martijn Pieters Feb 11 '18 at 00:32

1 Answers1

10

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,
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343