Python Arena
Step 3 of 5

Lists inside lists

The items of a list can be lists themselves:

teams = [["Ana", "Ben"], ["Cleo", "Dev", "Eli"], ["Finn"]]
print(teams)
print(teams[1])
print(teams[1][0])
print(len(teams), len(teams[1]))
Output
[['Ana', 'Ben'], ['Cleo', 'Dev', 'Eli'], ['Finn']]
['Cleo', 'Dev', 'Eli']
Cleo
3 3

Read teams[1][0] from left to right: teams[1] is the second team, which is a list, and [0] picks the first name in that list. The outer list has three items, and each of them happens to be a list.

A list as a record

A short list can also hold the facts about one thing, each at its own index. For a book, the title could be at index 0, the year at index 1 and the number of pages at index 2:

["The Glass Garden", 2011, 312]

A list of such lists is a small database. A for loop goes through it one record at a time:

books = [
    ["The Glass Garden", 2011, 312],
    ["Night Trains", 1998, 205],
    ["River of Salt", 2020, 448],
]

for book in books:
    title = book[0]
    year = book[1]
    pages = book[2]
    print(f"{title} ({year}), {pages} pages")
Output
The Glass Garden (2011), 312 pages
Night Trains (1998), 205 pages
River of Salt (2020), 448 pages

On each round, book is one of the inner lists. Copying its items into variables with clear names makes the rest of the loop easy to read.

Adding a record is an append of a whole list. Finding the best record works as it did with plain numbers, except that you compare one item of each record and keep the whole record:

books = [
    ["The Glass Garden", 2011, 312],
    ["Night Trains", 1998, 205],
    ["River of Salt", 2020, 448],
]
books.append(["Paper Moons", 1987, 260])

oldest = books[0]
for book in books:
    if book[1] < oldest[1]:
        oldest = book

print("Oldest:", oldest[0], oldest[1])
Output
Oldest: Paper Moons 1987

The weak spot of such a record is that you have to remember what each index means: nothing in book[2] says "pages". The dictionaries, a little later in this part, give each value a name instead.

Your task

Challenge 1 of 3

Each pet is a list of its name, its kind and its age. Fill in the blanks so the program prints:

Rex is a dog, 4 years old
Tom is a cat, 7 years old
Polly is a parrot, 12 years old

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

A shopping cart is a list of items, and each item is a list of a product's name, its price and the quantity: ["milk", 1.25, 2] is two bottles of milk at 1.25 each.

Write a function total_price(cart) that returns the total price of the cart. For example, total_price([["milk", 1.25, 2], ["bread", 2.5, 1]]) returns 5.0.