Python any()

Table of Contents

Introduction

The any() function in Python is used to check if at least one element is True in an iterable.

If you are looking for the way to solve such a problem then you are in the right place, keep reading this article to know how to use this feature best.

This article will explain all the peculiarities of the any() function with many examples.

Python any() function

The any() function in Python returns True if at least one element of an iterable is True, otherwise False.
If the iterable is empty the any() function returns False.

The syntax is very simple and the same for all iterables:

any(my_iterable)

By following this link you can find the official Python documentation.

In the following sections you will find examples for the most frequent iterables, i.e. lists, tuples, strings, dictionaries and sets.

Python any() function – Examples

Lists

A list can contain objects of various types.
Depending on the type of the elements in the list, the any() function will return True or False.

Check out these examples below:

print(any([False, False, False]))
print(any([False, True, False]))
print(any([1, 2, 3]))
print(any([1, 0, 2]))
print(any([]))

Output

False
True
True
True
False

Tuples

As in the case of lists, tuples can also contain objects of various types.
Depending on the type of the elements of the tuple, the any() function will return True or False.

Check out these examples below:

print(any((False, False, False)))
print(any((False, True, False)))
print(any((1, 2, 3)))
print(any((1, 0, 2)))
print(any(()))

Output

False
True
True
True
False

Strings

Strings are always verified (True) except for the empty string.

print(any("A Python string"))
print(any("False"))
print(any("0"))
print(any(""))

Output

True
True
True
False

Dictionaries

In the case of dictionaries, Python only checks the keys.
If the dictionary is empty, any() returns False.

print(any({0: False, 1: True}))
print(any({0: False, 2: True}))
print(any({"a_key": "a value"}))
print(any({}))

Output

True
True
True
False

Sets

As with lists and tuples, even for sets it is sufficient for an element to be True for the any() function to return True.
If the set is empty, False will be returned.

print(any({False, False, False}))
print(any({False, True, False}))
print(any({1, 2, 3}))
print(any({1, 0, 2}))
print(any({}))

Output

False
True
True
True
False

Conclusion

This post showed you how to check if there is at least one True element in an iterable using the any() function in Python.
In particular we have seen examples for the most common iterables that are lists, tuples, strings, dictionaries and sets.

I hope this post was useful to you and I invite you to ask in the comments below if you have any doubts or if you are in trouble.

Leave a Comment

Your email address will not be published. Required fields are marked *