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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay