DEV Community

Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com on

7 1

Analyzing python iterables with all() and any()

all() and any() are built-in functions that help analyze python iterables.

all()

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

Python 3.7.4

>>> x = [2, 3, 5, 1]
>>> all(x)
True

>>> x = [2, 3, 5, 0]
>>> all(x)
False

>>> x = []
>>> all(x)
True
Enter fullscreen mode Exit fullscreen mode

In the second instance, False is returned because of the 0 in the list. Note that this would not be the case if the 0 was a string.

>>> x = [2, 3, 5, '0']
>>> all(x)
True
Enter fullscreen mode Exit fullscreen mode

For checking dictionary values,

>>> x = {'item1': 'pen', 'item2': 'paper', 'item3': 'book'}
>>> all(x.values())
True

>>> x = {'item1': 'pen', 'item2': 'paper', 'item3': False}
>>> all(x.values())
False

>>> x = {}
>>> all(x)
True
Enter fullscreen mode Exit fullscreen mode

any()

any() returns True if any element of the iterable is true. If the iterable is empty, it returns False.

>>> x = [2, 3, 5, 1]
>>> any(x)
True

>>> x = [2, 3, 5, 0]
>>> any(x)
True

>>> x = [0, 0, 0, '0']
>>> any(x)
True

>>> x = [0, 0, 0, 0]
>>> any(x)
False

>>> x = []
>>> any(x)
False
Enter fullscreen mode Exit fullscreen mode

It also works the same for dictionaries:

>>> x = {'item1': 'pen', 'item2': 'paper', 'item3': 'book'}
>>> any(x)
True

>>> x = {'item1': 'pen', 'item2': 'paper', 'item3': False}
>>> any(x)
True

>>> x = {}
>>> any(x)
False
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
dbanty profile image
Dylan Anthony

Nice post! Worth that they will short circuit. Meaning all will return as soon as it sees a False and any will exit as soon as it sees True.

So if you’re going to have a bunch of calculated values you should use a generator of some sort rather than building the list in advance.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay