Logical all and any

Built-in functions all() and any() are applied to sequences (lists, tuples, etc.) and return a bool value.

all(iterable) — returns True if all elements in iterable are true (or if iterable is empty). any(iterable) — returns True if at least one element in iterable is true.

These functions can be used to check certain conditions across an entire dataset. For example, to check if all numbers are greater than zero, or if at least one number is greater than 10.

Important points:

  • For empty iterables, all() will return True, while any() will return False.
  • An element is considered false if its bool() equals False.
  • The functions stop at the first false element (for all) or first true element (for any).
nums = [1, 2, 0, 4, 5]

print(all(nums))
# False - because 0 is a false value

print(any(nums))
# True - there are elements that are true (not equal to 0)

empty_list = []
print(all(empty_list))
# True - for empty iterable all elements are true

print(any(empty_list))
# False - there is not a single true element

contains_10 = any([n > 10 for n in nums])
print(contains_10)
# False - no number is greater than 10

positive = all([n > 0 for n in nums])
print(positive)
# False - there are non-positive numbers

Comments (0)

Leave a comment