Hit enter after type your search item

What is any() function in Python?

The any() function in Python returns True if any elements of the iterable are True. The any() function takes an argument which is the iterable e.g. a list, dictionary, string, tuple etc. For example:

any(a_list)

If iterable is empty then any() function returns False.

How to use any() function

The general way for using the any() function is:

any(iterable)

An example of using lists in any function

The example below shows using lists in the any() function as iterator argument. Two lists are created; one that contains a few items and the other is empty.

The code:


The result:

True

False

As the second list is empty, the any() returned False. On the other hand, as 2, 4, 6 and “Python” will evaluate as True, so any() function returned True for the first list.

Using True/False values in a list example

This example should make things even clear:


The result:

True

False

True

Similarly, if you have an iterator that contains items like None, 0, ‘’, -0, 0.0 then any() function will also return False. See the example with a list below:


The output:

False

The reason is all these items i.e. 0, 0.0, -0, False, and None are evaluated as False. As any() function could not find any item that is evaluated as True, so the result is False.

If we had just one item that evaluates as True then see the result:


The output:

True

Because this time 1 is evaluated as True.

An example of any() function with dictionary

The example below is using three dictionaries to show how any() function works with a dictionary:


The result:

False

False

False

True

True

True

An example with string

As such, the string is also an iterator in Python; you may also use strings in the any() function. The example below shows output as using string objects in the any() function.


The output of above code:

Python any

This div height required for enabling the sticky sidebar