Opposite of any() function – Python

Photo of author
Written By M Ibrahim
gitpython iterableunpacking python-3.x

Quick Fix: not all(l)

The Problem:

Implement a Python function that is the opposite of any(). The function should take an iterable as input and return True if any element in the iterable is False or equivalent to False (like an empty string or an empty list), and False otherwise.

The Solutions:

Solution 1: Using `not all(iterable)`

The Python built-in function `all(iterable)` returns `True` if all elements in the iterable are `True`, and `False` otherwise. Therefore, we can use the `not` operator to invert the result of `all(iterable)`, effectively returning `True` if any element in the iterable is `False`.

def any_false(iterable):
    return not all(iterable)

Solution 2: Not-Any Syntax

Write a generator expression which tests your custom condition. You’re not bound to only the default *truthiness* test:

“`
any(not i for i in l)
“`

Solution 3: Reverse Any Elements

The `any()` function checks if any element in an iterable is True. To achieve the opposite, where it returns True only if all elements are False, we can create a custom function `reverse_any()`:

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

This function iterates through each element in `iterable`, and if any element is False, it returns True. If the loop completes without finding a False element, it returns False.

Solution 4: Jack Aidley’s Solution

The most efficient way to achieve the opposite effect of `any(iterable)` in Python is to use the following function:

def any_false(l):
    return not all(l)

This function will return `True` if any element in the iterable is `False` and `False` otherwise.