Python any & all function


In this tutorial, you will learn about Any & all function in python.

 

Introduction


In Python, the any() and all() functions are built-in functions that operate on iterables, allowing you to check if any or all elements in the iterable satisfy a certain condition.

These functions are particularly useful when dealing with boolean values or conditions applied to a collection of items.

 

any() Function


The any() function returns True if at least one element in the iterable is true. If the iterable is empty, it returns False.

Syntax

any(iterable)

iterable: The iterable (e.g., list, tuple) to be checked for truthiness.

Basic Example

numbers = [0, 3, 5, 7, 9]
result = any(x > 5 for x in numbers)
print(result)  # Output: True

In this example, the any() function checks if at least one number in the list is greater than 5.

 

all() Function


The all() function returns True if all elements in the iterable are true. If the iterable is empty, it returns True.

Syntax

all(iterable)

iterable: The iterable (e.g., list, tuple) to be checked for truthiness.

Basic Example

numbers = [2, 4, 6, 8, 10]
result = all(x % 2 == 0 for x in numbers)
print(result)  # Output: True

Here, the all() function checks if all numbers in the list are even.

 

Use Cases


Checking Conditions in Lists

grades = [85, 92, 78, 94, 89]
passing = all(grade >= 70 for grade in grades)
print(passing)  # Output: True

In this case, all() checks if all grades are greater than or equal to 70.

Validating User Input

user_inputs = ["Alice", 25, "Bob", 30]
valid_input = all(isinstance(item, str) for item in user_inputs)
print(valid_input)  # Output: False

Here, all() is used to check if all elements in the list are of type string.

Combining with any()

numbers = [2, 4, 7, 10]
result = any(x % 2 == 0 for x in numbers) and all(x > 5 for x in numbers)
print(result)  # Output: False

This example demonstrates how you can use both any() and all() in combination to check multiple conditions.

 

Conclusion


The any() and all() functions in Python provide convenient ways to check the truthiness of elements in an iterable. They are valuable tools for expressing conditions concisely and are commonly used in scenarios where you need to validate or verify a set of conditions across a collection of items. Understanding how to use these functions can lead to more readable and expressive code.
 

© 2022-2023 All rights reserved.