list1 = [2,4,5,6,7,89]
lambdafunction = lambda x: x > 20
print(any(lambdafunction(list1)))
I basically want it to print true or false on the condition x > 20 if any of the numbers in the list are greater than 20. How would I do that using an 'any' function and a lambda? I know how to check for a specific position in the list, but not how to check the whole list.
To keep it functional you could use map
:
list1 = [2,4,5,6,7,89]
lambdafunction = lambda x: x > 20
print(any(map(lambdafunction, list1)))
map
returns an iterator in python3 so the values will be lazily evaluated. If the first element in your lists is > 20, not more values will be consumed from the iterator.
In [1]: list1 = [25,4,5,6,7,89]
In [2]: lambdafunction = lambda x: x > 20
In [3]: it = map(lambdafunction, list1)
In [4]: any(it)
Out[4]: True
In [5]: list(it)
Out[5]: [False, False, False, False, True]
You can do:
>>> print(any(lambdafunction(x) for x in list1))
True
Or even:
>>> print(any(x > 20 for x in list1))
True
This iterates over the elements of the list and it checks that each element is greater than 20. The any()
function takes care of returning the correct answer. In your solution you're not iterating over each element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With