BYU logo Computer Science

Writing functions with lists

Example: Accumulator Pattern

This example demonstrates the accumulator pattern. By accumulation, we mean calculating a single value as we iterate, like taking a sum or an average.

def get_sum(numbers):
    total = 0
    for number in numbers:
        total = total + number
    return total


result = get_sum([3, 5, 9]);

In the get_sum() function, we initialize the total variable to zero. Then, each time we iterate through the numbers, we increase total by the current number.

Here is a chart showing how this code updates the number and total variables each time through the loop. Iteration number 0 is where we start before the for loop.

Iterationnumbertotal
0N/A0
133
258
3917

At the end of the function, it returns the final value for total, which is 17.

We then get result = 17 after the function get_sum() is done.

Example: Mapping Pattern

This example illustrates the mapping pattern. By mapping we mean that we start with a list and use its values to calculate and return a new list.

def bigger(numbers):
    bigger_numbers = []
    for number in numbers:
        bigger = number * 2
        bigger_numbers.append(bigger)

    return bigger_numbers

result = bigger([4, 7, 11])

In the bigger() function, the argument to the function is a list of numbers. We want to create and return a new list of numbers that has all the original numbers multiplied by 2.

We start by initializing a variable called bigger_numbers to an empty list, shown as []. Then, as we iterate through the list, we calculate a bigger number and then append it to the list.

Here is a chart that shows each step of the iteration:

Iterationnumberbiggerbigger_numbers
0N/AN/A[]
148[8]
2714[8, 14]
31122[8, 14, 22]

At the end of the function, it returns the final value for bigger_numbers, which is [8, 14, 22].

We then get result = [8, 14, 22] after the function bigger_numbers() is done.

Example: Filter Pattern

This example illustrates the mapping pattern. By filter we mean that we start with a list and use its values to calculate and return a new list that has some or all of the original values.

def only_odds(numbers):
    odds = []
    for number in numbers:
        if number % 2 != 0:
            odds.append(number)
    return odds


result = only_odds([2, 3, 4, 5])

This function takes a list of numbers and returns a new list that has only the odd numbers from the original list.

We start by initializing a variable odds to an empty list. We then iterate through the list and check if each number is odd. We can do this by using the mod operator, %, which calculates the remainder, and check if the remainder is zero. If it is not zero, then we have an odd number, so we can append it to the list we store in the odds variable.

The function finishes by returning odds, so eventually the result variable will store [3, 5].

Example: Selection Pattern

This example illustrates the selection pattern, which chooses a single value from a list, such as a minimum or maximum value.


def find_min(numbers):
    smallest = None
    for number in numbers:
        if smallest is None or number < smallest:
            smallest = number
    return smallest


result = find_min([10, 8, 40, 22, 3, 5])

Here we are trying to calculate the minimum value of a list of numbers. We start by initializing smallest to None, because there is no smallest number yet. Then, when we iterate over the list, we do two checks with an if statement. First, we check if smallest is still None. If it is, that means we haven’t found a smallest number yet, so the one we are currently looking at must be the smallest. Second, we check if the current number is smaller than smallest. If either of these checks succeeds, we set smallest = number.

Here is a chart for the iterations of the loop:

Iterationnumbersmallest
0N/ANone
11010
288
3408
4228
533
653

At the end, result = 3.

Notice that if we ran this code:

result = find_min([])

then we would get result = None.

Example: Finding the average

This example uses the accumulator pattern again.

def average(numbers):
    total = 0
    for number in numbers:
        total = total + number
    return total / len(numbers)


result = average([1, 2, 3, 4])

We sum up all of the numbers, like did in get_sum(), above. However, at the end, instead of returning total, we return total / len(numbers), which gives us the average.