Skip to content
Home » The ALL and ANY Built-in Functions

The ALL and ANY Built-in Functions

Spread the love

Today we’ll briefly discuss the two built-in functions: all and any. They are very handy and make our life easier, but these are again examples of something you could live without. There are other ways in Python of achieving the same results, as you are about to see.

Here’s the video version:

These two functions work on any iterable: a string, a list, a dictionary, a range, and so on.

The all Function

The all function can be thought of as a series of and operators. It returns True if all the elements in the iterable are True and False otherwise.

So, instead of using multiple and operators like this:

>>> 2 + 3 == 5 and 'a' in 'car' and 5 and True
True

we can use the all function. The function requires one argument, so we have to pass all the elements enclosed in a list or tuple for example:

>>> all([2 + 3 == 5, 'a' in 'car', 5, True])
True 

The any Function

The any function can be thought of as a series of or operators. It returns True if any of the elements in the iterable is True and False otherwise.

So, instead of using multiple or operators like this:

>>> len("hi") > 10 or 0 or 3 ** 2 == 9 or 'abc'[0] == 'a'
True

we can use the any function. The function also requires one argument, so we have to pass all the elements enclosed in a list or tuple again,  for example:

>>> any([len("hi") > 10, 0, 3 ** 2 == 9, 'abc'[0] == 'a'])
True

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Short-Circuited Execution with all and any

Both all and any short-circuit the execution. As soon as it’s known what the result will be, the other elements in the iterable are omitted. For example in the following code:

>>> all((3, 0, 4, 7, 3, 8))
False

The execution will be short-circuited at the second element because at this moment it’ll be clear that the result is False.

Similarly, in the following code:

>>> any([0, False, '', 2, 1 > 2, [], {}, None, True])
True

execution will be short-circuited at the element 2, because if at least one element is True, the result is True. By the way, all non-zero and non-empty objects are regarded as True.

We can use any iterables. Comprehensions also return iterables, so they can be used:

words = ['cat', 'car', 'cliff', 'color', 'cow']
>>> all(word.startswith('c') for word in words)
True
>>> any(len(word) > 3 for word in words)
True

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply