Search code examples
pythonpython-3.xlistany

How do I obtain the value that caused any() to return True?


When I call the any() function, it returns only True or False. If it returns True, how can I obtain the element that caused it to return True?

all = ['azeri', 'english', 'japan', 'india', 'indonesia']
lg = 'from japan'
lgn = lg.split()
if any(word in lgn for word in all):
      print(word)

In this case, I'd like to obtain the word japan. This code, as written, just returns NameError: name 'word' is not defined.


Solution

  • You are correct in your assumption that any returns True or False based on the fact that condition matches for any element in the iterable. But this is not how you extract the element which satisfied the condition

    From the docs: https://docs.python.org/3/library/functions.html#any

    any(iterable)
    Return True if any element of the iterable is true. If the iterable is empty, return False.

    In your case, since the condition is met, the print statement will execute as below. But since word is only within the scope of the generator inside any, you get the error NameError: name 'word' is not defined.
    Also you should not name your variable all since it will shadow the builtin all

    In [15]: all = ['azeri', 'english', 'japan', 'india', 'indonesia'] 
        ...: lg = 'from japan' 
        ...: lgn = lg.split() 
        ...: if any(word in lgn for word in all): 
        ...:     print('condition met') 
        ...:                                                                                                                                                                                                                     
    condition met
    

    If you want to find the list of words satisfying the condition, you should use a for-loop in say a list-comprehension

    all_words = ['azeri', 'english', 'japan', 'india', 'indonesia']
    lg = 'from japan'
    lgn = lg.split()
    
    #Find words which are present in lgn
    res = [word for word in all_words if word in lgn]
    
    print(res)
    

    The output will be ['japan']