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]))
[['Ana', 'Ben'], ['Cleo', 'Dev', 'Eli'], ['Finn']]
['Cleo', 'Dev', 'Eli']
Cleo
3 3Read 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")
The Glass Garden (2011), 312 pages
Night Trains (1998), 205 pages
River of Salt (2020), 448 pagesOn 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])
Oldest: Paper Moons 1987The 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.