I have a question about returning a value of the any
function in Python.
Here is the code:
def check():
for l in lines:
ret = any(word in l for word in list)
return ret
It only returns a bool, but I need the word which matched with the list.
For example:
If I have the string "In school they're eating for lunch a lot of unhealthy food"
and the list ["lunch", "burger", "sushi"]
then I would need the word "lunch"
.
In Python 3.8, the assignment expression can be used to capture the witness that causes any
to return True
.
for l in lines:
if any((x:=word) in l for word in list):
return x
If any
returns True
, it is because the value of word
(assigned to x
) caused word in l
to be true. x
and word
are bound in different scopes: word
in the scope of the generator expression, x
in the scope where the generator expression is defined.