any() and all() in Python

Today we will discuss two functions in Python, ‘any’ and ‘all’ and their different examples. Python provides two built-in functions ‘any()’ and ‘all()’ to perform “AND” and “OR” operations.

Python any() function

Syntax: any(iterable)

It takes an iterable object as a parameter.

Return Value: 

It can have two types of the return value:

  • True: The any() function returns True if at least one item in the iterable is true.
  • False: The any() function returns False either if the iterable is empty or if none of the items in the iterable results as true.

It works similar to a sequence of ‘OR’ operations over the given iterable. It will stop the execution once we get the result.

Examples: any() function in Python

# any() function for a list
list1 = [ 0, False, 1, False]
x = any(list1)
print(x)

# any() function for a dictionary
dict1 = { 0 : "monday", 1: "tuesday"}
x = any(dict1)
print(x)

# any() function for a set
set1 = {False, False}
x = any(set1)
print(x)

Output:

True
True
False

Python all() function

Syntax: any(iterable)

It takes an iterable object as a parameter.

Return Value: 

It can have two types of the return value:

  • True: The all() function returns True either if the iterable is empty or if each and every item in the iterable is true.
  • False: The all() function returns False even if a single item in the iterable is false.

It works similar to a sequence of ‘AND’ operations over the given iterable. It will stop the execution once we get the result.

Examples:

# any() function for a list
list1 = [ 0, False, 1, False]
x = any(list1)
print(x)

# any() function for a dictionary
dict1 = { 1 : "monday", 1: "tuesday"}
x = any(dict1)
print(x)

# any() function for a set
set1 = {True, True}
x = all(set1)
print(x)

Output:

False
True
True

Leave a Reply

Your email address will not be published.