Skip to content

Python any lambda

  • by

Using any lambda you can check for any element satisfying a condition and returns True in case it finds any True value in Python.

Python any lambda example

Simple example code.

good_foods = ['apple', 'carrot']
junk_foods = ['soda', 'burger']

my_foods = ['banana', 'carrot', 'bread', 'apple', 'soda']

result = (any(map(lambda x: x in junk_foods, my_foods)))

print(result)

Output:

Python any lambda

How to achieve python’s any() with a custom predicate?

Answer: Use a generator expression inside of any():

l = list(range(10))
pred = lambda x: x > 10

if any(pred(i) for i in l):
print("foo")
else:
print("bar")

Do comment if you have any doubts or suggestions so this Python any() function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading