In Python, the any()
and all()
functions are built-in functions that operate on iterables such as lists, tuples, or sets. They provide a concise way to check the truthiness of multiple elements within an iterable. Here’s a breakdown of each function:
any(iterable)
: The any()
function returns True
if at least one element in the iterable is considered truthy, and False
if all elements are considered falsy or the iterable is empty. It stops iterating through the elements as soon as it encounters the first truthy element.
numbers = [0, 1, 2, 3, 4]
result = any(numbers)
print(result) # Output: True
all(iterable)
: The all()
function returns True
if all elements in the iterable are considered truthy, and False
if any element is considered falsy or the iterable is empty. It stops iterating through the elements as soon as it encounters the first falsy element.
numbers = [1, 2, 3, 4]
result = all(numbers)
print(result) # Output: True
Python any all example
Here’s an example that combines the any()
and all()
functions in Python:
numbers = [2, 4, 6, 8, 9]
# Check if any number is divisible by 2 (even)
# #and if all numbers are greater than 0
result_any = any(num % 2 == 0 for num in numbers)
result_all = all(num > 0 for num in numbers)
print(result_any)
print(result_all)
Output:
In the above example, we have a list of numbers. We use any()
to check if any number in the list is divisible by 2 (even) by using a generator expression (num % 2 == 0 for num in numbers)
. Since there are even numbers in the list, the result_any
is True
.
Next, we use all()
to check if all numbers in the list are greater than 0 by using the generator expression (num > 0 for num in numbers)
. Since there is a number (9
) that is not greater than 0, the result_all
is False
.
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.