This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: More functions

any/all

face Josiah Wang

Let’s take a break from all these object-oriented programming, and go back to cover some topics related to functions.

Now, let say you have a list of numbers and want to check whether any of them is an even number. You might end up using a for loop for this.

import random

# generate a random list of 10 numbers
numbers = [random.randint(0, 50) for i in range(10)]

any_even = False
for number in numbers:
    if number % 2 == 0:
       any_even = True 
       break
print(any_even)

There is an arguably more readable way to accomplish this, using Python’s built-in any() function.

import random
numbers = [random.randint(0, 50) for i in range(10)]
any_even = any(number%2==0 for number in numbers)
print(any_even)

In this version, you simply pass an iterable (e.g. a list) to the any() function. The function will check whether ANY element in the list is True, and return True if so.

In this example, number%2==0 for number in numbers generates something like [False, False, True, False, True, ...]. So any() will return True is at least one element is True.

What if you need to check whether ALL numbers in the list are True? Easy - use the all() function instead!

import random
numbers = [random.randint(0, 50) for i in range(10)]
all_even = all(number%2==0 for number in numbers)
print(all_even)

If you think carefully, any() is equivalent to a series of or operators, and all() equivalent to a series of and operators. These functions make your code more readable than like the one below.

import random
numbers = [random.randint(0, 50) for i in range(4)]
if number[0]%2 == 0 and numbers[1]%2 == 0 and numbers[2]%2 == 0 and numbers[3]%2 == 0:
    all_even = True
else:
    all_even = False

We won’t do any exercises for this (phew!), but any() and all() are functions that is worth knowing! Who knows when you might need it?