any() and all() in Python with Examples

Introduction to any() and all()

In this tutorial, we'll be covering the any() and all() functions in Python.

The any(iterable) and all(iterable) are built-in functions in Python and have been around since Python 2.5 was released. Both functions are equivalent to writing a series of or and and operators respectively between each of the elements of the passed iterable. They are both convenience functions that shorten the code by replacing boilerplate loops.

Both methods short-circuit and return a value as soon as possible, so even with huge iterables, they're as efficient as they can be.

The and/or Operators

Let's remind ourselves how the and/or operators work, as these functions are based on them.

The or Operator

The or operator evaluates to True if any of the conditions (operands) are True.

print("(2 == 2) or (3 == 3) evaluates to: " + str((2 == 2) or (3 == 3)))
print("(2 == 2) or (3 == 2) evaluates to: " + str((2 == 2) or (3 == 2)))
print("(2 == 0) or (3 == 2) evaluates to: " + str((2 == 0) or (3 == 2)))

Output:

(2 == 2) or (3 == 3) evaluates to: True
(2 == 2) or (3 == 2) evaluates to: True
(2 == 0) or (3 == 2) evaluates to: False

We can chain multiple ors in a single statement, and it will again evaluate to True if any of the conditions are True:

print(str(False or False or False or True or False))

This results in:

True

The and Operator

The and operator evaluates to True only if all conditions are True:

print("(2 == 2) and (3 == 3) evaluates to: " + str((2 == 2) and (3 == 3)))
print("(2 == 2) and (3 == 2) evaluates to: " + str((2 == 2) and (3 == 2)))
print("(2 == 0) and (3 == 2) evaluates to: " + str((2 == 0) and (3 == 2)))

Output:

(2 == 2) and (3 == 3) evaluates to: True
(2 == 2) and (3 == 2) evaluates to: False
(2 == 0) and (3 == 2) evaluates to: False

Similarly to or, we can chain multiple and operators, and they will evaluate to True only if all the operands evaluate to True:

print(str(True and True and True and False and True))

This results in:

False

any()

The method any(iterable) behaves like a series of or operators between each element of the iterable we passed. It's used to replace loops similar to this one:

for element in some_iterable:
    if element:
        return True
return False

We get the same result by simply calling any(some_iterable):

print(any([2 == 2, 3 == 2]))
print(any([True, False, False]))
print(any([False, False]))

Running this piece of code would result in:

True
True
False

Note: Unexpected behavior may happen when using any() with dictionaries and data types other than boolean. If any() is used with a dictionary, it checks whether any of the keys evaluate to True, not the values:

dict = {True : False, False: False}

print(any(dict))

This outputs:

True
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Whereas, if any() checked the values, the output would have been False.

The method any() is often used in combination with the map() method and list comprehensions:

old_list = [2, 1, 3, 8, 10, 11, 13]
list_if_even = list(map(lambda x: x % 2 == 0, old_list))
list_if_odd = [x % 2 != 0 for x in old_list]

print(list_if_even)
print(list_if_odd)

print("Are any of the elements even? " + str(any(list_if_even)))
print("Are any of the elements odd? " + str(any(list_if_odd)))

This outputs:

[True, False, False, True, True, False, False]
[False, True, True, False, False, True, True]
Are any of the elements even? True
Are any of the elements odd? True

Note: If an empty iterable is passed to any(), the method returns False.

If you'd like to read more about the map(), filter() and reduce() functions, we've got you covered!

all()

The all(iterable) method evaluates like a series of and operators between each of the elements in the iterable we passed. It is used to replace loops similar to this one:

for element in iterable:
    if not element:
        return False
return True

The method returns True only if every element in iterable evaluates to True, and False otherwise:

print(all([2 == 2, 3 == 2]))
print(all([2 > 1, 3 != 4]))
print(all([True, False, False]))
print(all([False, False]))

This outputs:

False
True
False
False

Note: Just like with any(), unexpected behavior may happen when passing dictionaries and data types other than boolean. Again, if all() is used with a dictionary, it checks whether all of the keys evaluate to True, not the values.

Another similarity with any() is that all() is also commonly used in combination with the map() function and list comprehensions:

old_list = ["just", "Some", "text", "As", "An", "example"]
list_begins_upper = list(map(lambda x: x[0].isupper(), old_list))
list_shorter_than_8 = [len(x) < 8 for x in old_list]

print(list_begins_upper)
print(list_shorter_than_8)

print("Do all the strings begin with an uppercase letter? " + str(all(list_begins_upper)))
print("Are all the strings shorter than 8? " + str(all(list_shorter_than_8)))

This outputs:

[False, True, False, True, True, False]
[True, True, True, True, True, True]
Do all the strings begin with an uppercase letter? False
Are all strings shorter than 8? True

Note: If an empty iterable is passed to all(), the method returns True! This is because the code for all() checks if there are any False elements in the iterable, and in the case of an empty list there are no elements and therefore there are no False elements either.

Boolean Conversion and any(), all() Functions

A common cause of confusion and errors when using any logical operators, and therefore when using any() and all() as well, is what happens when the elements aren't of the boolean data type. In other words, when they aren't exactly True of False but instead have to be evaluated to True or False.

Some programming languages don't evaluate non-boolean data types to booleans. For example Java would complain if you tried something along the lines of if("some string") or if(15) and tell you that the type you used can't be converted to boolean.

Python on the other hand does no such thing, and will instead convert what you passed to boolean without warning you about it.

Python converts most things to True with a few exceptions:

  • Any numerical value equal to 0 (including 0.0) is treated as False. A common misconception here is that negative values (-2, -3.3,...) are treated as False as well, they are not treated as False!
  • Any empty sequence (or collection) is treated as False, including empty strings, empty lists, etc. Keep in mind that unexpected behavior might happen when using all() with an empty iterable (it will return True).
  • The actual boolean value False is of course treated as False as well as the special value None.

A few examples of how we can use the way Python "boolean-izes" other data types with any() and all().

list_of_strings = ["yet", "another", "example",""]
print("Do all strings have some content?", all(list_of_strings))

list_of_ints = [0, 0.0, -2, -5]
print("Are any of the ints different from 0?", any(list_of_ints))

This outputs:

Do all strings have some content? False
Are any of the ints different from 0? True

Keep in mind that you might still want to write more readable code by not using implicit boolean conversion like this.

Conclusion

Both the any() and all() functions are there for convenience sake and should be used only when they make the code shorter but maintain the readability.

In this article, we've jumped into the any() and all() functions and showcased their usage through several examples.

Last Updated: September 11th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Olivera PopovićAuthor

LinkedIn: https://rs.linkedin.com/in/227503161
If you need any help - post it in the comments :) That way someone else can reply if I'm busy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms