Python Any | [Explained] any() Function in Python

There are many built-in functions in Python. Which helps us in increasing our productivity and efficiency in coding. One of the built-in function in Python interpreter is python any().

Python any() takes iterable as an argument and returns True if any of the element in the iterable is true. If iterable is empty, then the Python any() Function returns False.

Different Iterables Which Can Be Used With any() Function

While using the Python any() the iterable can be of different types. Some of the iterable’s are that can be used with Python any() function are the following:

  • list
  • generator
  • string
  • dictionary
  • tuples
  • boolean
  • empty iterables
  • custom objects

Python any() Syntax:

any(iterable)

Parameters

The iterable object can be a list, tuple, boolean, dictionary etc.

The return type of any()

Python any() returns true if any of the items is True. It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.
Its short circuit the execution i.e. stop the execution as soon as the result is known.

Truth Table of Python any() Function

Python any() Function Truth Table

Sample Frame / Blueprint of Python Function()

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

Now, Let’s see some examples of Python any() with different iterables.

any() Function With List

list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].

Let’s try to use any() with a list :

# If all values are true
list1 = [9, 5, 11, True]
print(any(list1))

# If all values are false
list2 = [0, False]
print(any(list2))

# If one value is false, others are true
list3 = [5, 16, 3, 15]
print(any(list3))

# If one value is true, others are false
list4 = [10, 0, False, 19]
print(any(list4))

# empty iterable
list5 = []
print(any(list5))

Output:

True
False
True
True
False

any() Function With Tuples

tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses (), whereas lists use square brackets []. Creating a tuple is as simple as putting different comma-separated values.

Let’s try to use any() with a tuple :

# If all values are true
tuple1 = (9, 5, 11, True)
print(any(tuple1))

# If all values are false
tuple2 = (0, False)
print(any(tuple2))

# If one value is false, others are true
tuple3 = (5, 16, 3, 15)
print(any(tuple3))

# If one value is true, others are false
tuple4 = (10, 0, False, 19)
print(any(tuple4))

# empty iterable
tuple5 = ()
print(any(tuple5))

Output:

True
False
True
True
False

any() Function With String

string in Python is a sequence of characters. It is a derived data type. Strings are immutable. This means that once defined, they cannot be changed.

A string is also iterable and we can use Python any() on a string object as well.
Let’s try to use any() with strings:

#First String
string1 = "Python Pool"
print(any(string1))

#Second String
string2 = 'Karan Singh Bhakuni'
print(any(string2))

#Third String
string3 = "55 56"
print(any(string3))

#Fourth String
string4 = '26 Python Pool the best place to learn python'
print(any(string4))

#Fifth String
string5 = ()
print(any(string5))

Output:

True
True
True
True
False

As you can see that only for the empty string, it results False. For non-empty strings, the result is always True. This is another way to check if a string is empty or not.

any() Function With Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds the key: value pair. Key-value is provided in the dictionary to make it more optimized.

Python any() Function will check only the keys,i.e. if anyone of the keys is true, it will result True. Else, False.
Let’s try to use any() with strings:

# When all keys are true
dict1 = {1: 'True', 2: 'True'}
print(any(dict1))

# When all keys are false
dict2 = {0: 'False', False: 'True'}
print(any(dict2))

# When one key is true, others are false
dict3 = {1: 'Karan', 0: 'Pool', False: 'Python'}
print(any(dict3))

# When one key is false, others are true
dict4 = {0: 'False', 'True': 'Python', 1: 'Pool'}
print(any(dict4))

# When dictionary is empty
dict5 = {}
print(any(dict5))

Output:

True
False
True
True
False

Note:

In case of dictionaries, if all keys (not values) are false, any() returns False. If at least one key is true, any() returns True.

Python any() Function With Boolean

In programming, you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and returns the Boolean answer.

Let’s try to use any() with booleans:

# If all values are true
bool1 = [True,  True]
print(any(bool1))

# If all values are false
bool2 = [False, False]
print(any(bool2))

# If one value is false, others are true
bool3 = [False, True, True, True]
print(any(bool3))

# If one value is true, others are false
bool4 = [True, False, False]
print(any(bool4))

# empty iterable
bool5 = []
print(any(bool5))

Output:

True
False
True
True
False

Python any() Function With Sets

A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table.

A set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.
Let’s try to use any() with sets:

# If all values are true
set1 = {True,  True}
print(any(set1))

# If all values are false
set2 = {False, 0}
print(any(set2))

# If one value is false, others are true
set3 = {False, 1, True, True}
print(any(set3))

# If one value is true, others are false
set4 = {True, False, 0}
print(any(set4))

# empty iterable
set5 = {}
print(any(set5))

Output:

True
False
True
True
False

Using any() Method to Check If List Contains Any Element of Other List

In this example, we are taking two lists. In both of the list, we are taking city names as the elements of the list.

# Program to check the list contains elements of another list using any()

# List1
List1 = ['Newyork' ,  'London', 'Sidney', 'Chicago', 'Madrid', 'Paris']
 
# List2
List2 = ['Seattle' , 'Chicago', 'Prague']

#Using any function to check
check =  any(item in List1 for item in List2)
 
if check is True:
    print("The list {} contains some elements of the list {}".format(List1, List2))    
else :
    print("No, List1 doesn't have any elements of the List2.")

Output:

The list ['Newyork', 'London', 'Sidney', 'Chicago', 'Madrid', 'Paris'] contains some elements of the list ['Seattle', 'Chicago', 'Prague']

Here in list 1 and list 2, we checked for the common elements. And as you can see there is a common element (Chicago) which is present in both of the list. So the Output says list1 contains some elements of lsit2.

Must Read:

Conclusion

You can use Python any() in any iterable to check quickly if all values are False or not. Any Returns true if any of the items is True. It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.

Try to run the programs on your side and let me know if you have any queries.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments