Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all, no values in the iterable are falsy;
  • in the case of any, at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-boolean elements in the iterable are perfectly acceptable — bool(x) maps, or coerces, any x according to these rules:

  • 0, 0.0, None, [], (), [], set(), and other empty collections are mapped to False
  • all other values are mapped to True.

The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.

For example:

if all(x > 0 for x in xs) or any(x > 100 for x in xs):
    # if nothing is zero or something is over a hundred …

In your specific code samples:

You’ve slightly misunderstood how these functions work. The following does something completely different from what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator or a generator expression (≈ lazily evaluated/generated list), or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to the value held by big_foobar, and (lazily) emits the resulting boolean into the resulting sequence of booleans:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Answer from Erik Kaplun on Stack Overflow
Top answer
1 of 2
190

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all, no values in the iterable are falsy;
  • in the case of any, at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-boolean elements in the iterable are perfectly acceptable — bool(x) maps, or coerces, any x according to these rules:

  • 0, 0.0, None, [], (), [], set(), and other empty collections are mapped to False
  • all other values are mapped to True.

The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.

For example:

if all(x > 0 for x in xs) or any(x > 100 for x in xs):
    # if nothing is zero or something is over a hundred …

In your specific code samples:

You’ve slightly misunderstood how these functions work. The following does something completely different from what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator or a generator expression (≈ lazily evaluated/generated list), or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to the value held by big_foobar, and (lazily) emits the resulting boolean into the resulting sequence of booleans:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

2 of 2
0

For the question in the title:

if a list contains one set of values or another

it might be more natural to use set operations. In other words, instead of

if any(x==playerOne for x in board) or any(x==playerTwo for x in board):

# or 
if playerOne in board or playerTwo in board:

use set.issubset (or set.intersection1):

if {playerOne, playerTwo}.issubset(board):

# or
if {playerOne, playerTwo} & set(board):

If playerOne and playerTwo are set/list/tuple of values, then compute their union and test if it's a subset of board:

if {*playerOne,*playerTwo}.issubset(board):

Also if the question is

if every item on the board is either playerOne marker or playerTwo marker

then instead of

if all(x == playerOne or x == playerTwo for x in board):

test set equality:1

if {playerOne, playerTwo} == set(board):

1 You can obviously assign set(board) to some variable beforehand so that you don't have to cast board to a set every time you need to test this condition.

🌐
W3Schools
w3schools.com › python › ref_func_any.asp
Python any() Function
Remove List Duplicates Reverse ... Certificate Python Training ... The any() function returns True if any item in an iterable are true, otherwise it returns False....
Discussions

python - Pythonic way of checking if a condition holds for any element of a list - Stack Overflow
I have a list in Python, and I want to check if any elements are negative. Is there a simple function or syntax I can use to apply the "is negative" check to all the elements, and see if ... More on stackoverflow.com
🌐 stackoverflow.com
How do Python's any and all functions work? - Stack Overflow
The confusion can be that "FOR ALL" and "FOR ANY" are synonyms in other contexts... en.wikipedia.org/wiki/List_of_logic_symbols 2017-01-26T09:10:16.997Z+00:00 ... I know this is old, but I thought it might be helpful to show what these functions look like in code. This really illustrates the logic, better than text or a table IMO. In reality they are implemented in C rather than pure Python... More on stackoverflow.com
🌐 stackoverflow.com
Is there a more efficient way to check if at least one value is present in a list of values?
You can use any with a generator. if any(item in z for item in x, y): This will short-circuit, ie it will exit as soon as it finds an item that fulfils the criteria. More on reddit.com
🌐 r/learnpython
7
1
July 19, 2022
How to check if any element in a list contains a substring
If you don't need to know exactly which element(s) contain the substring, then you could use the any built-in function in combination with a list comprehension l = ["Hey dude", "Hey bro", "Sup dude", "Hey bud"] substring = "Sup" if any([substring in element for element in l]): print(f"One or more elements of {l} contain the substring {substring}") else: print(f"No elements of {l} contain the substring {substring}") Here's an explanation about the any function. Alternatively, switch out any for all if you want to check if all the elements of the list contain the substring. all documentation More on reddit.com
🌐 r/learnpython
18
11
October 28, 2019
🌐
Dot Net Perls
dotnetperls.com › any-python
Python - any, all List Methods - Dot Net Perls
When the lists has all zero elements, any returns false. But when we add a 1, any returns true. So Any() requires at least one element that does not evaluate to False. Zero evaluates to False. # Test any with all zero elements. # ... These evaluate to false. values = [ ... 0] result = any(values) ...
🌐
DataCamp
datacamp.com › tutorial › python-any-function
Python any() Function: Guide With Examples and Use Cases | DataCamp
July 31, 2024 - The any() function in Python returns True if at least one element in an iterable (list, tuple, set, etc.) is true, and False otherwise.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-any-function
Python any() function - GeeksforGeeks
July 23, 2025 - In this example, the any() function in Python checks for any element satisfying a condition and returns True in case it finds any True value. This function is particularly useful to check if all/any elements in List meet condition in Python.
🌐
Programiz
programiz.com › python-programming › methods › built-in › any
Python any()
Become a certified Python programmer. Try Programiz PRO! ... The any() function returns True if any element of an iterable is True. If not, it returns False. ... The any() function takes an iterable (list, string, dictionary etc.) in Python.
🌐
Vultr Docs
docs.vultr.com › python › built-in › any
Python any() - Check Any True Values | Vultr Docs
September 27, 2024 - This code checks the list bool_list for any True values. Since there is one True value in the list, any() returns True. Realize that non-zero numbers are treated as True in Python.
Find elsewhere
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Use all() and any() in Python | note.nkmk.me
May 12, 2025 - In Python, you can use the built-in functions all() and any() to check whether all elements or at least one element in an iterable (such as a list or tuple) evaluate to True. Built-in Functions - all( ...
🌐
freeCodeCamp
freecodecamp.org › news › python-any-and-all-functions-explained-with-examples
Python any() and all() Functions – Explained with Examples
August 10, 2021 - As shown in the code snippet below, our example string coding**is**cool**345 contains digits. Therefore, calling any() function on the string should return True. We use list comprehension to get a list of True and False values depending on whether the character is a digit or not.
🌐
Career Karma
careerkarma.com › blog › python › how to use python any and all: a step-by-step guide
How to Use Python Any and All: A Step-By-Step Guide | Career Karma
December 1, 2023 - The Python any() method calculates whether any value in an iterable object—a list, string, or tuple—is equal to True and returns True; otherwise, any() returns False.
🌐
Flexiple
flexiple.com › python › python-list-contains
Python list contains: How to check if an item exists in list? - Flexiple
Each method has its specific use case, ensuring Python developers have the necessary tools to efficiently work with list data structures. Using set() combined with the in operator is an effective Python strategy for checking if an element exists in a list, especially when dealing with large datasets.
🌐
GeeksforGeeks
geeksforgeeks.org › python-check-if-any-element-in-list-satisfies-a-condition
Check if any element in list satisfies a condition-Python - GeeksforGeeks
February 11, 2025 - Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range.Using any() Function -
🌐
Python Morsels
pythonmorsels.com › any-and-all
Python's any() and all() functions - Python Morsels
March 29, 2023 - Need to check whether all items in a list match a certain condition? You can use Python's built-in any and all functions for that!
🌐
GeeksforGeeks
geeksforgeeks.org › any-all-in-python
Any All in Python - GeeksforGeeks
December 1, 2023 - In this another example, we are seeing of all numbers in list1 are odd and by using all() function, if they are odd then we will return True otherwise False. ... # Illustration of 'all' function in python 3 # Take two lists list1=[] list2=[] # All numbers in list1 are in form: 4*i-3 for i in range(1,21): list1.append(4*i-3) # list2 stores info of odd numbers in list1 for i in range(0,20): list2.append(list1[i]%2==1) print('See whether all numbers in list1 are odd =>') print(all(list2))
🌐
Real Python
realpython.com › any-python
How to Use any() in Python – Real Python
February 18, 2022 - In the above example, you check each applicant’s credentials and schedule an interview if the applicant meets any of your three criteria. Technical Detail: Python’s any() and or aren’t limited to evaluating Boolean expressions. Instead, Python performs a truth value test on each argument, evaluating whether the expression is truthy or falsy.
🌐
Stack Abuse
stackabuse.com › any-and-all-in-python-with-examples
any() and all() in Python with Examples
September 11, 2023 - Keep in mind that unexpected behavior might happen when using all() with an empty iterable (it will return True). The actual boolean value False is of course treated as False as well as the special value None. A few examples of how we can use the way Python "boolean-izes" other data types with any() and all(). list_of_strings = ["yet", "another", "example",""] print("Do all strings have some content?", all(list_of_strings)) list_of_ints = [0, 0.0, -2, -5] print("Are any of the ints different from 0?", any(list_of_ints))
🌐
BeginnersBook
beginnersbook.com › 2019 › 03 › python-any-function
Python any() Function with examples
March 18, 2019 - Python any() function accepts iterable (list, tuple, dictionary etc.) as an argument and return true if any of the element in iterable is true, else it returns false.
Top answer
1 of 11
442

You can roughly think of any and all as series of logical or and and operators, respectively.

any

any will return True when at least one of the elements is Truthy. Read about Truth Value Testing.

all

all will return True only when all the elements are Truthy.

Truth table

+-----------------------------------------+---------+---------+
|                                         |   any   |   all   |
+-----------------------------------------+---------+---------+
| All Truthy values                       |  True   |  True   |
+-----------------------------------------+---------+---------+
| All Falsy values                        |  False  |  False  |
+-----------------------------------------+---------+---------+
| One Truthy value (all others are Falsy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| One Falsy value (all others are Truthy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| Empty Iterable                          |  False  |  True   |
+-----------------------------------------+---------+---------+

Note 1: The empty iterable case is explained in the official documentation, like this

any

Return True if any element of the iterable is true. If the iterable is empty, return False

Since none of the elements are true, it returns False in this case.

all

Return True if all elements of the iterable are true (or if the iterable is empty).

Since none of the elements are false, it returns True in this case.


Note 2:

Another important thing to know about any and all is, it will short-circuit the execution, the moment they know the result. The advantage is, entire iterable need not be consumed. For example,

>>> multiples_of_6 = (not (i % 6) for i in range(1, 10))
>>> any(multiples_of_6)
True
>>> list(multiples_of_6)
[False, False, False]

Here, (not (i % 6) for i in range(1, 10)) is a generator expression which returns True if the current number within 1 and 9 is a multiple of 6. any iterates the multiples_of_6 and when it meets 6, it finds a Truthy value, so it immediately returns True, and rest of the multiples_of_6 is not iterated. That is what we see when we print list(multiples_of_6), the result of 7, 8 and 9.

This excellent thing is used very cleverly in this answer.


With this basic understanding, if we look at your code, you do

any(x) and not all(x)

which makes sure that, atleast one of the values is Truthy but not all of them. That is why it is returning [False, False, False]. If you really wanted to check if both the numbers are not the same,

print [x[0] != x[1] for x in zip(*d['Drd2'])]
2 of 11
58

How do Python's any and all functions work?

any and all take iterables and return True if any and all (respectively) of the elements are True.

>>> any([0, 0.0, False, (), '0']), all([1, 0.0001, True, (False,)])
(True, True)            #   ^^^-- truthy non-empty string
>>> any([0, 0.0, False, (), '']), all([1, 0.0001, True, (False,), {}])
(False, False)                                                #   ^^-- falsey

If the iterables are empty, any returns False, and all returns True.

>>> any([]), all([])
(False, True)

I was demonstrating all and any for students in class today. They were mostly confused about the return values for empty iterables. Explaining it this way caused a lot of lightbulbs to turn on.

Shortcutting behavior

They, any and all, both look for a condition that allows them to stop evaluating. The first examples I gave required them to evaluate the boolean for each element in the entire list.

(Note that list literal is not itself lazily evaluated - you could get that with an Iterator - but this is just for illustrative purposes.)

Here's a Python implementation of any and all:

def any(iterable):
    for i in iterable:
        if i:
            return True
    return False # for an empty iterable, any returns False!

def all(iterable):
    for i in iterable:
        if not i:
            return False
    return True  # for an empty iterable, all returns True!

Of course, the real implementations are written in C and are much more performant, but you could substitute the above and get the same results for the code in this (or any other) answer.

all

all checks for elements to be False (so it can return False), then it returns True if none of them were False.

>>> all([1, 2, 3, 4])                 # has to test to the end!
True
>>> all([0, 1, 2, 3, 4])              # 0 is False in a boolean context!
False  # ^--stops here!
>>> all([])
True   # gets to end, so True!

any

The way any works is that it checks for elements to be True (so it can return True), then it returnsFalseif none of them wereTrue`.

>>> any([0, 0.0, '', (), [], {}])     # has to test to the end!
False
>>> any([1, 0, 0.0, '', (), [], {}])  # 1 is True in a boolean context!
True   # ^--stops here!
>>> any([])
False   # gets to end, so False!

I think if you keep in mind the short-cutting behavior, you will intuitively understand how they work without having to reference a Truth Table.

Evidence of all and any shortcutting:

First, create a noisy_iterator:

def noisy_iterator(iterable):
    for i in iterable:
        print('yielding ' + repr(i))
        yield i

and now let's just iterate over the lists noisily, using our examples:

>>> all(noisy_iterator([1, 2, 3, 4]))
yielding 1
yielding 2
yielding 3
yielding 4
True
>>> all(noisy_iterator([0, 1, 2, 3, 4]))
yielding 0
False

We can see all stops on the first False boolean check.

And any stops on the first True boolean check:

>>> any(noisy_iterator([0, 0.0, '', (), [], {}]))
yielding 0
yielding 0.0
yielding ''
yielding ()
yielding []
yielding {}
False
>>> any(noisy_iterator([1, 0, 0.0, '', (), [], {}]))
yielding 1
True

The source

Let's look at the source to confirm the above.

Here's the source for any:

static PyObject *
builtin_any(PyObject *module, PyObject *iterable)
{
    PyObject *it, *item;
    PyObject *(*iternext)(PyObject *);
    int cmp;

    it = PyObject_GetIter(iterable);
    if (it == NULL)
        return NULL;
    iternext = *Py_TYPE(it)->tp_iternext;

    for (;;) {
        item = iternext(it);
        if (item == NULL)
            break;
        cmp = PyObject_IsTrue(item);
        Py_DECREF(item);
        if (cmp < 0) {
            Py_DECREF(it);
            return NULL;
        }
        if (cmp > 0) {
            Py_DECREF(it);
            Py_RETURN_TRUE;
        }
    }
    Py_DECREF(it);
    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
            PyErr_Clear();
        else
            return NULL;
    }
    Py_RETURN_FALSE;
}

And here's the source for all:

static PyObject *
builtin_all(PyObject *module, PyObject *iterable)
{
    PyObject *it, *item;
    PyObject *(*iternext)(PyObject *);
    int cmp;

    it = PyObject_GetIter(iterable);
    if (it == NULL)
        return NULL;
    iternext = *Py_TYPE(it)->tp_iternext;

    for (;;) {
        item = iternext(it);
        if (item == NULL)
            break;
        cmp = PyObject_IsTrue(item);
        Py_DECREF(item);
        if (cmp < 0) {
            Py_DECREF(it);
            return NULL;
        }
        if (cmp == 0) {
            Py_DECREF(it);
            Py_RETURN_FALSE;
        }
    }
    Py_DECREF(it);
    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
            PyErr_Clear();
        else
            return NULL;
    }
    Py_RETURN_TRUE;
}
🌐
Analytics Vidhya
analyticsvidhya.com › home › any() and all() in python with examples
any() and all() in Python with Examples - Analytics Vidhya
April 1, 2024 - Master any() and all() functions in Python to efficiently handle collections like lists and tuples. Understand functions with examples.