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

2

6

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.

Flotage answered 18/5, 2019 at 4:23 Comment(2)
Beware: naming your variable with all shadows a built-in function.Disillusionize
why not just: for word in lgn: print(word) if word in all else None ? in your example word is defined only inside the any call so you cannot access itOusel
D
5

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']

Doriedorin answered 18/5, 2019 at 4:27 Comment(2)
This is a good solution, but I want a string to be the output. So I would make a code like, for word in lgn: if word in all_words: print(word) else: None; like what @Ousel saidFlotage
Okay, they you can just print the elements of res in a for loop @ArmandDwiDoriedorin
K
3

As per your requirement i think, you should be using just filter instead of any. The below code should work.

all = ['azeri', 'english', 'japan', 'india', 'indonesia']
lg = 'from japan'
lgn = lg.split()

print(list(filter(lambda word: word in lgn, all))) 
Kokanee answered 18/5, 2019 at 5:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.