lettura simple

Python's all() Function

The all() function is a handy built-in feature provided by Python. Essentially, it comes back with True if every element within an iterable object holds a truthy value, or even if the iterable happens to be empty. Conversely, if there's even a single element that doesn't pass the truthy check, it replies with False.

all(oggetto)

Here, the function invites just one argument, the iterable object - this could be a list, a tuple, or anything else you might want to run a truthy check on.

Let's walk you through an illustrative example to shed more light on this.

Kick things off by creating a list that houses four elements.

>>> myList = [1, 3, 4, 5]

Next up, use the all() function to see if every element within the list is truthy.

>>> all(myList)

Since each element in our list is indeed truthy (non-zero), the function gets back to us with a True.

True

Bear in mind that in Python's world, anything non-null is regarded as True.

Let's switch gears a bit and craft a list that contains a zero.

>>> myList = [0, 1, 3, 4, 5]

Now, bring the all() function into play again to verify the list's content.

>>> all(myList)

This time around, the all() function stumbles upon a null element - the zero in our list. As a result, it returns False.

False

For our final act, let's see how the all() function behaves when faced with an empty iterable object.

Set up an empty list.

>>> myList = []

Engage the all() function once more to check if there are any non-null elements lurking in there.

>>> all(lista)

In this scenario, the all() function responds with True. Even though it doesn't have any elements to evaluate, it doesn't run into any non-null elements either.

True




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin