Python any(): A Built-In Function for Truth Testing Collections

Tired of writing loops every time you need to check the elements of a collection? Python's any() function almost makes this syntactic task fun--allowing devs to shrink complex logic into one-liners.
python any built in function alpharithms

The Python any function tests each element of an iterable against a condition. It is invaluable as a filtering function and be combined with other language features. Used with features like lambdas or list comprehensions, Python’s any() function makes incredibly powerful statements with syntactic ease.

Python’s any() function performs a test of truthiness for each member of a collection. This means every element is considered against a conditional such that a value of either True or False is returned. The any() function is best used in cases where a membership test is needed but characteristics of each member need to be considered.

Introduction

Python’s any() function can be used simply to check if a value meets a simple condition or in more complex cases where additional functions, objects, and operands are used to assess a condition. In this article we’ll take a look at how the any() function is used, starting with simple examples and moving through some more complex cases.

TL;DR – To check all items of an iterable using the any() function one can use the following syntax:

# Define an empty list
nums = []

# Check if empty
any(nums)

>>> False

# Add some values to nums
nums.extend([1, 3, 8, 3, 9, 5, 3, 0, 7, 6])

# Check if any non integer values present
any(type(x) != int for x in nums)

>>> False

# Check if any value above 10
any(x > 10 for x in nums)

>>> False

# Check if any even numbers 
print(any(x % 2 == 0 for x in nums))

>>> True

As described by the official documentation, Python’s any() function will “return True if any element of an iterable is True. If the iterable is empty, return False.” Equivalently, the documentation offers the following example:

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

This showcases the logic implemented by the any() function but fails to convey all the creative opportunities it provides developers. We’ll cover some basic uses of any() as well as some more advanced approaches to better understand just how useful this function really is.

Basic Example

Python’s robust language features are one of the reasons it continues to be one of the most popular programming languages. The Python built-in functions are an excellent example of such features—simplifying many commonly used operations for developers.

Python’s any() built-in function is one such feature and can greatly simplify the syntax needed for elementwise checking of iterable objects like lists, dicts, and tuples.

Before we dive too deeply let’s check out a simple example of the benefits offered by the any() function. Here, we’ll simply check whether a list of random numbers contains an even number.

# Create a list of random numbers
numbers = [3, 6, 4, 7, 4, 9, 6, 6, 3, 7]

# Define a function to check if 9 is in the list
def has_nine():
    for number in numbers:
        if number == 9:
            return True
    return False

# Check the list 
has_nine()
>>> True

Here we see a traditional approach to checking an iterable for a condition—looping over the list. This function is horribly contrived and only suited for this use case. The issue in creating such a function is that one needs to have a condition specific to each case. Here, our condition is if number == 9. Python’s any() function allows a much more flexible approach:

# Check if any value is equal to 9
any(x == 9 for x in numbers)

>>> True

Here we see our comparison reduced to a single line of code. This example showcases the functionality of any() well enough but isn’t very practical. For example, 9 in numbers would be a comparable assertion and doesn’t require any use of functions—built-in or otherwise. To get a better example of using the any() function let’s mix in some complexity.

More Examples

The any() function really starts to show its value when we introduce some complexity in our use of conditionals. Before we were simply assessing whether a member of the numbers collection was equal to the value 9. Now, let’s consider how we can have a bit more fun:

# Check if any two unique numbers add to be greater than 10
any(x + y > 10 for x in numbers for y in numbers if x is not y)

>>> True

# Check if any number is greater than 2 standard deviations
# from the mean of the numbers
from statistics import mean, stdev

# Use any to check each number
any(x > mean(numbers) + stdev(numbers) * 2 for x in numbers)

>>> False

Breaking Things

It’s important to keep in mind that the any() function accepts an iterable as an argument. Passing a single value into any() will cause Python to throw a TypeError exception. Consider the following examples:

# Pass a single element
any(1)

>>> TypeError: 'int' object is not iterable

# Pass a single element in a list
any([1])

>>> True

# Pass multiple elements as non-iterable
any(1, 2)

>>> TypeError: any() takes exactly one argument (2 given)

# Pass multiple empty collections
any([], [])

>>> TypeError: any() takes exactly one argument (2 given)

# Pass empty collection
any([])

>>> False  # no error 

# Pass a single string
any("alpha")

>>> True

# Pass a single character string
any("0")

>>> True

# Convert a string to a int via eval
any(eval("0"))

>>> TypeError: 'int' object is not iterable

These examples showcase the nuances by which the any() function will nag about having multiple arguments or non-iterables. In summary, we now see the following is true for use of the any() function:

  1. Only a single argument can be given;
  2. Only an iterable object can be passed as the argument;
  3. Strings—even as a single character—are iterables and can be passed to any;
  4. Casting a string to a non-iterable will be interpreted as an invalid argument

Note: The any() and all() functions are quite similar. However, any() will return on the first element meeting the Truthy condition where all() will return on the first element failing to meet the Truthy condition. In a sense, they are complements of one another. Read more about Python’s all() built in here.

Final Thoughts

The any() function is among the most useful of the Python built-in functions. Its use case is broad and provides developers with a constant opportunity to reduce syntactic mass. Whether your goal is to be as Pythonic as possible, to develop in as few lines of code as possible, or just chain together the longest one-liner possible—Python’s any() function can lend a hand.

One other benefit of the any() function is that it will return True on the first truthy element—be that implied by the presence or evaluated by conditional via a more complex argument. I like to think of the any() function as a membership test that considers the characteristics of each member. If simply knowing an item is in a collection isn’t enough—that’s when any() is most useful!

alpharithms discord banner 1
Zαck West
Entrepreneur, programmer, designer, and lifelong learner. Can be found taking notes from Mother Nature when not hammering away at the keyboard.