Skip to content

8 min read

American Corners

Lists

What a list is

So far each variable has held one value: a number, a word, a turtle. But a lot of real work involves many values at once, like the names of everyone helping at the workshop, or the sun hours recorded every month for eighty years. A list lets you keep all of them together in one ordered container.

You make a list with square brackets and separate the items with commas. The items can be strings, numbers, or anything else.

teaching_assistants = ["Ana", "Ben", "Dea", "Ilir", "Nora"]
ages = [15, 15, 16, 14, 15]

A list is ordered, which means each item has a fixed position. That position is called its index, and Python counts positions from 0, not from 1. So in the list above, "Ana" is at index 0, "Ben" is at index 1, and "Dea" is at index 2. You read an item by putting its index in square brackets.

print(teaching_assistants[2])
# Dea

Tip

The most common mistake with lists is forgetting that counting starts at 0. The first item is list[0], and the last item of a five-item list is list[4], not list[5]. Asking for an index that does not exist stops the program with an error.

Building and changing a list

A list is not frozen once you make it. You can add to it, remove from it, and reorder it while the program runs.

To add one item to the end, use append. New assistants keep arriving, so:

teaching_assistants = ["Ana", "Ben", "Dea", "Ilir", "Nora"]
teaching_assistants.append("Sara")
print(teaching_assistants)
# ['Ana', 'Ben', 'Dea', 'Ilir', 'Nora', 'Sara']

To visit every item in order, loop over the list directly. You do not need indexes for this.

for name in teaching_assistants:
    print(name)

To take an item out, use remove with the value itself. To slot a new item in at a chosen position, use insert with the index first and the value second. And pop removes the last item and hands it back to you.

teaching_assistants.remove("Ilir")      # drop Ilir by name
teaching_assistants.insert(1, "Uran") # put Uran at index 1
last = teaching_assistants.pop()          # remove and keep the last one
print(teaching_assistants)
# ['Ana', 'Uran', 'Ben', 'Dea', 'Nora']

Two more tools you will reach for constantly. len tells you how many items a list holds, and slicing pulls out a run of items using two indexes, the start and the stop. As with everything in Python, the stop index is not included.

print(len(teaching_assistants))
# 5
print(teaching_assistants[1:3])
# ['Uran', 'Ben']

Solving problems with lists

Once you can hold a batch of numbers, most real questions become a short loop over that batch. Here are three small functions that come up again and again: the largest number, the total, and just the odd ones.

def max_list(numbers):
    largest = numbers[0]
    for n in numbers:
        if n > largest:
            largest = n
    return largest

def sum_list(numbers):
    total = 0
    for n in numbers:
        total += n
    return total

def odds_list(numbers):
    result = []
    for n in numbers:
        if n % 2 == 1:
            result.append(n)
    return result

Each one follows the same shape: start with an answer so far, walk through the list one item at a time, and update the answer. odds_list builds a brand new list with append instead of tracking a single number. Trying them out:

ages = [15, 15, 16, 14, 15, 14]
print(max_list(ages))   # 16
print(sum_list(ages))   # 89
print(odds_list(ages))  # [15, 15, 15]

Nested loops and the data world

Sometimes one loop is not enough. Suppose you have 4 t-shirt colours and 3 jeans colours and you want every possible outfit. For each shirt you have to run through all the jeans, which is a loop inside a loop.

shirts = ["white", "red", "blue", "green"]
jeans = ["light blue", "dark blue", "black"]

for shirt in shirts:
    for jean in jeans:
        print(shirt + " t-shirt, " + jean + " jeans")

The outer loop picks a shirt and holds it still while the inner loop lists all three jeans, then the outer loop moves to the next shirt. Four shirts times three jeans gives twelve outfits.

This same pattern is how you work through data. A list can hold other lists, which is exactly how a table of numbers looks in Python: one inner list per row. Here is a small slice of real data, the sun hours recorded in Oxford, with one row per year and one column per month.

data = [
    [43.8, 60.5, 190.2],   # year 1: Jan, Feb, Mar
    [49.9, 54.3, 109.7],   # year 2
    [63.7, 72.0, 142.3],   # year 3
]

monthly_mean = []
n = len(data)            # number of years
for m in range(3):       # one column per month
    s = 0
    for year in data:    # walk down the rows
        s += year[m]     # add this year's value for month m
    monthly_mean.append(s / n)

print(monthly_mean)
# roughly [52.5, 62.3, 147.4]

The outer loop fixes a month, the inner loop adds up that month across every year, and the average goes into monthly_mean. With the full eighty years of data the same eight lines would tell you which month in Oxford has the best weather. That is the whole idea of programming in a data world: a small, clear loop doing the counting that no person would want to do by hand.

Lab

Extend the data list with a fourth month by adding one more number to each row, then change range(3) to range(4) so the loop covers it. Run it and check that monthly_mean now has four averages.

Check yourself

  1. In the list ["Ana", "Ben", "Dea"], what index holds "Dea", and what would print(list[3]) do?
  2. What is the difference between append and insert when you add an item to a list?
  3. In the nested sun-hours loop, why does the total s get reset back to 0 at the start of each month rather than once at the very beginning?

Where this lesson comes from

Built from

  • Programming in a Data World: Lecture 6 deck (Lists + nested loops)
  • Lecture Notebook: Oxford sun-hours nested-list data analysis

alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.

This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.

Found something unclear, outdated or improvable? Suggest an improvement