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']
all
shadows a built-in function. – Disillusionizefor word in lgn: print(word) if word in all else None
? in your exampleword
is defined only inside theany
call so you cannot access it – Ousel