any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):
Answer from Ken on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_any.asp
Python any() Function
Python Examples Python Compiler ... Certificate Python Training ... The any() function returns True if any item in an iterable are true, otherwise it returns False....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-any-function
Python any() function - GeeksforGeeks
July 23, 2025 - In this example, the any() function is used to check if any value in the list is True. If at least one element in the Python list is True, it will return 'True'; otherwise, it will return 'False'.
Discussions

python - Using any() and all() to check if a list contains one set of values or another - Stack Overflow
My code is for a Tic Tac Toe game and checking for a draw state but I think this question could be more useful in a general sense. I have a list that represents the board, it looks like this: board... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a way of saying "If any condition resulted in True do A else B"
๐ŸŒ r/Python
82
10
May 19, 2023
How do Python's any and all functions work? - Stack Overflow
I'm trying to understand how the any() and all() Python built-in functions work. I'm trying to compare the tuples so that if any value is different then it will return True and if they are all the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
What in-house tools are you building or using for network automation?
A lot of teams Iโ€™ve seen build a mix of Python scripts and Ansible playbooks on top of NetBox or Nautobot for inventory, config generation, and drift detection. The biggest wins are usually automating repetitive tasks and having a single source of truth, but integration and keeping everything up to date can get tricky fast. More on reddit.com
๐ŸŒ r/networking
75
58
February 17, 2026
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-any-function
Python any() Function: Guide With Examples and Use Cases | DataCamp
July 31, 2024 - 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().
๐ŸŒ
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.
๐ŸŒ
Real Python
realpython.com โ€บ any-python
How to Use any() in Python โ€“ Real Python
February 18, 2022 - Pythonโ€™s any() and or return different types of values. any() returns a Boolean, which indicates whether it found a truthy value in the iterable: ... In this example, any() found a truthy value (the integer 1), so it returned the Boolean value ...
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Use all() and any() in Python | note.nkmk.me
May 12, 2025 - Convert between bool (True/False) and other types in Python ยท These rules also apply when determining truth values in all() and any(). all() returns True if all elements in the given iterable evaluate to true.
Find elsewhere
๐ŸŒ
Mostly Python
mostlypython.com โ€บ using-any
Using `any()`
January 23, 2025 - MP 132: It's a simple built-in function, but using it isn't as straightforward as it might seem. A task that's come up repeatedly in my programming work involves looking through a collection of values, and taking an action if a specific item appears anywhere in that collection. There's a way
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ functions.html
Built-in Functions โ€” Python 3.14.3 documentation
1 month ago - Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to: def any(iterable): for element in iterable: if element: return True return False
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-any-and-all-functions-explained-with-examples
Python any() and all() Functions โ€“ Explained with Examples
August 10, 2021 - Let's understand the syntax of the any() function, look at some simple examples, and then proceed to more useful examples. ... Returns True if bool(x) is True for any x in the iterable.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ any-and-all
Python's any() and all() functions - Python Morsels
March 29, 2023 - The any function checks for the truthiness of each item in a given iterable, but we need something a little more than that: we need to check a condition on each element. Specifically, we need to check whether a number is between 0 and 5. Python ...
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ built-in โ€บ any
Python any() - Check Any True Values | Vultr Docs
September 27, 2024 - The any() function in Python checks if any element in an iterable is True. This function is extremely useful when you need a quick way to evaluate if at least one of the conditions in a composite query returns True.
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 โ€บ python_conditions.asp
Python If Statement
The if statement evaluates a condition (an expression that results in True or False). If the condition is true, the code block inside the if statement is executed. If the condition is false, the code block is skipped.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-check-if-any-element-in-list-satisfies-a-condition
Check if any element in list satisfies a condition-Python - GeeksforGeeks
July 12, 2025 - For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the condition. any() is the most efficient way to check if any element in a list satisfies a condition.
๐ŸŒ
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 - Thatโ€™s where the Python built-in functions any() and all() come in. any() iterates through every item in an object and returns True if any item is equal to True.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-and-when-to-use-any-and-all-in-python
How and when to use any() and all() in Python
On the other hand, the second print statement prints False because none of the elements are True, i.e., all elements are False. The any() function checks if at least one character in the string is a digit.
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ any() and all() in python with examples
any() and all() in Python with Examples - Analytics Vidhya
April 1, 2024 - Checking for Specific Attributes in a List of Dictionaries ... The any() follows a straightforward syntax: any(iterable) yields True if at least one element within the iterable is evaluated as true and False otherwise.
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ is there a way of saying "if any condition resulted in true do a else b"
r/Python on Reddit: Is there a way of saying "If any condition resulted in True do A else B"
May 19, 2023 -

Hello,

I was wondering if there is any way to do something like this:

if condition1:
    do1()
elif condition2:
    do2()
elif condition3:
    do3():
else:
    default()
if any condition resulted in True:
    doA()
if all resulted in False:
    doB()

The logical approach would be to create some flag variable or to add the `doA()`-call to every if statement. But I feel like that many people are using constructs like this and there should a more clever/elegant way of solving this.

Have a nice day!

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;
}