any() and all() in Python with Examples

python_tutorials

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 finish reading, please visit source site