Course
A common requirement in Python programs is to check whether at least one element of a data structure is True
.
Although it's possible to write a loop to iterate through an iterable and check whether each item evaluates to True
or False
, Python's any()
function is a more efficient and Pythonic way to achieve this result.
This tutorial explores Python's any()
built-in function and shows several examples and use cases for this function.
AI Upskilling for Beginners
What Does Python's any()
Function Do?
Python's any()
is one of the built-in functions. It accepts an iterable such as a list or tuple, and it returns True
if at least one value in the iterable is truthy. A truthy value is evaluated as True
when cast to a Boolean using bool()
. If all values in the iterable are falsy, any()
returns False
:
print(any([True, False, False, True]))
print(any([False, False, False, False]))
print(any([0, 0, 5, 0]))
True
False
True
The iterable can contain Boolean values or other objects since all objects are evaluated as True
or False
when cast to a Boolean. In the third example, the list includes four integers. The integer 0
is falsy, but all non-zero numbers are truthy. To better understand the difference between truthy and falsy values, read this blog on Python logical operators.
If the iterable is empty, any()
returns False
since there are no truthy values in an empty iterable:
print(any([]))
False
The next section dives deeper into how any()
works.
How Does any()
Work?
The built-in any()
accepts any iterable as its argument. An iterable is any data structure Python can loop through.
Consider the following tuple:
an_iterable = ("", 0.0, "DataCamp", False, [])
The tuple includes several objects with different types. Several of these objects are falsy:
- The empty string
""
- The float
0.0
- The Boolean
False
- The empty list
[]
These objects are falsy since they are evaluated as False
when passed to bool()
.
The non-empty string "DataCamp"
is truthy.
A straightforward way of checking whether at least one element is truthy is to use a for
loop:
def check_if_contains_truthy(data):
output = False
for item in data:
if item:
output = True
return output
print(check_if_contains_truthy(an_iterable))
True
However, this is inefficient since the function only needs to check whether there's at least one truthy value. Once it finds a truthy value, it doesn't need to continue checking the rest of the iterable's items. The function can be modified to return as soon as it finds the first truthy value:
def check_if_contains_truthy(data):
for item in data:
if item:
return True
return False
print(check_if_contains_truthy(an_iterable))
True
A return
statement stops the function's execution. Therefore, when the function finds the first truthy value, it returns True
and doesn't continue iterating over the iterable. The function returns False
only if the for
loop iterates through all the items in the iterable and none of them is truthy.
The built-in any()
follows a similar pattern and short-circuits when it finds the first truthy value. This lazy evaluation prevents unnecessary operations, which improves performance. Python's any()
is a more efficient version of the function shown above. This improved efficiency is confirmed using the timeit()
function from the timeit
module, which times how long Python takes to execute a statement:
from timeit import timeit
print("Execution time for 'check_if_contains_truthy()'")
print(
timeit(
"check_if_contains_truthy(an_iterable)",
number=10_000_000,
globals=globals(),
)
)
print("Execution time for 'any()'")
print(
timeit(
"any(an_iterable)",
number=10_000_000,
globals=globals(),
)
)
Execution time for 'check_if_contains_truthy()'
0.6335119580035098
Execution time for 'any()'
0.39488654200249584
The timeit()
function's first argument is a string containing the statement to execute. The second argument determines how often to run the statement. In this example, both statements are executed 10,000,000 times to get meaningful times. The final argument passes the global variables to the timeit()
function.
Python's any()
is faster than check_if_contains_truthy()
. Using any()
to find whether an iterable has at least one truthy value is more Pythonic and efficient than using a for
loop.
Use Cases for any()
Let's look at some use cases for Python's any()
.
Check if at least one user input is valid
Consider a series of user inputs collected in a list or tuple. A program may need to check whether at least one of the inputs is valid, such as if it's a non-empty string:
user_inputs = ["", "10.99", ""]
if any(user_inputs):
print("At least one valid input present")
# Rest of code...
else:
print("There are no valid inputs")
At least one valid input present
Since one of the strings is not empty, any()
returns True
, and the code in the if
clause is executed.
Check if at least one file exists
The built-in any()
can be used to check if at least one file in a list of filenames exists in a directory:
from pathlib import Path
files = ["article.md", "use_any.py", "scratch.py", "test_file.txt"]
cwd = Path.cwd()
# Create a test file to test code
Path("test_file.txt").write_text("This is a test file")
if any(Path(file).exists() for file in files):
print("At least one of the files exists")
# Rest of code…
else:
print("None of the files exist")
At least one of the files exists
The code fetches the current working directory using the pathlib
module and Path.cwd()
. It creates a file called test_file.txt
in the working directory to ensure that this code can be tested easily. Python's any()
is used to check whether at least one of the filenames exists in the current working directory.
Filter items from an iterable
The built-in function any()
can also be used with a generator expression as an argument and filter items from an iterable. In this example, any()
looks for at least one entry in a list of dictionaries that represents a person whose age is below 18
:
records = [
{"name": "Sarah", "age": 23},
{"name": "Jake", "age": 30},
{"name": "Paul", "age": 17},
]
if any(record["age"] < 18 for record in records):
print("There's at least one minor.")
else:
print("All records are adults.")
There's at least one minor.
The generator expression yields True
or False
depending on the value corresponding to each dictionary's "age"
key. A generator expression can be used in any()
as it's iterable.
Revisiting lazy evaluation in Python's any()
The previous example can also demonstrate that any()
is evaluated lazily. Consider the following modification to the list of dictionaries:
records = [
{"name": "Sarah", "age": 23},
{"name": "Jake", "age": 30},
{"name": "Paul", "age": 17},
{"name": "Jill"},
]
if any(record["age"] < 18 for record in records):
print("There's at least one minor.")
else:
print("All records are adults.")
There's at least one minor.
The fourth dictionary in records
doesn't contain an item with the key "age"
. However, the code doesn't raise an error when trying to fetch the value corresponding to "age"
for this item since any()
found a truthy value earlier in the process. The function short-circuits when it encounters the first truthy value.
The code raises a KeyError
if the dictionary that's missing the key "age"
comes before any items with an age below 18
:
records = [
{"name": "Jill"},
{"name": "Sarah", "age": 23},
{"name": "Jake", "age": 30},
{"name": "Paul", "age": 17},
]
if any(record["age"] < 18 for record in records):
print("There's at least one minor.")
else:
print("All records are adults.")
Traceback (most recent call last):
...
if any(record["age"] < 18 for record in records):
~~~~~^^^^^^
KeyError: 'age'
This example is designed to demonstrate the short-circuiting behavior when using Python's any()
. There's an alternative if the code shouldn't raise exceptions for items without an "age"
key. The code can use the dictionary method .get()
with a default value instead of accessing a dictionary value using the square brackets notation. The if
statement can be replaced with the following version if the default behavior is to assume that entries with no age aren't minors:
if any(record.get("age", 18) < 18 for record in records):
# ...
If the code should assume that any entry without an age is a minor, the default value needs to be a value lower than 18
.
Python: any()
vs. all()
Python's any()
has a companion function, all()
. This built-in function also accepts an iterable and returns True
if all the iterable's items are truthy.
Consider an example from earlier in this tutorial to validate user inputs. Python's any()
is useful if the application requires at least one valid input. However, all()
can be used if all user inputs should be valid:
user_inputs = ["", "10.99", ""]
if any(user_inputs):
print("At least one valid input present")
# Rest of code...
else:
print("There are no valid inputs")
if all(user_inputs):
print("All inputs are valid")
# Rest of code...
else:
print("Not all inputs are valid")
At least one valid input present
Not all inputs are valid
However, if all the strings in the user inputs are non-empty, all()
returns True
:
user_inputs = ["5.99", "10.99", "19.99"]
# …
At least one valid input present
All inputs are valid
Similarly to any()
, the built-in all()
is evaluated lazily. The function short-circuits when it finds the first falsy value.
Conclusion
Python's any()
finds whether any of the items in an iterable is truthy. The function returns True
if at least one item in the iterable is True
or evaluates to True
when cast to a Boolean. Although the same output can be achieved using a loop, this built-in function offers a more readable and efficient solution.
Earn a Top AI Certification
I studied Physics and Mathematics at UG level at the University of Malta. Then, I moved to London and got my PhD in Physics from Imperial College. I worked on novel optical techniques to image the human retina. Now, I focus on writing about Python, communicating about Python, and teaching Python.