4
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.

4
  • Why do you want to use a lambda? It's not needed here.. Commented Sep 11, 2015 at 22:43
  • Just for a class, we're suppose to practice lambda functions in a few different forms. A regular function would make more sense here though. Commented Sep 11, 2015 at 23:02
  • Actually just using a generator expression makes the most sense.. any(x>20 for x in list1) Commented Sep 11, 2015 at 23:04
  • cool! yeah that does make it easier. Commented Sep 11, 2015 at 23:12

4 Answers 4

4

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]
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

You could do something like this:

list1 = [2,4,5,6,7,89]
lambdafunction = lambda x: [item > 20 for item in x]
print(any(lambdafunction(list1)))

lambdafunction would return an array of booleans which would be if each element in the array is greater than 20. Then, you could use any to see if any of them are true.

But I would recommend using a regular function (using def) if possible.

1 Comment

You should use lambdafunction = lambda x: (item > 20 for item in x)
1

You are looking for filter function.

print(any(filter(lambdafunction, list1)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.