Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.4: lambda function using a list

Tags:

python

lambda

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.

like image 756
cjoy Avatar asked Jan 07 '23 14:01

cjoy


2 Answers

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]
like image 178
Padraic Cunningham Avatar answered Jan 23 '23 13:01

Padraic Cunningham


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.

like image 20
Simeon Visser Avatar answered Jan 23 '23 13:01

Simeon Visser