Many Cards: Lists and for Loops
So far every variable has held a single value: one number, one string. Real programs often work with many values of the same kind, such as several questions, several names or several scores. Python keeps such values together in a list, and a for loop runs the same lines once for every value in it, so a program can handle three values or three hundred with the same code.
A list holds several values in order
A list is one value that holds other values, called its items, in a fixed order. You write a list by putting the items between square brackets, with a comma between each pair:
cities = ["Paris", "Rome", "Oslo"]
scores = [7, 9, 4, 10]
nothing = []
print(cities)
print(len(cities))
print(len(nothing))['Paris', 'Rome', 'Oslo']
3
0The name cities now refers to the whole list, just as a name could refer to a single number before. When Python prints a list of strings, it shows the brackets and puts single quotes round each string, so you can see where every item begins and ends.
The order is part of the list: ["Paris", "Rome", "Oslo"] and ["Oslo", "Rome", "Paris"] are two different lists. The same value may also appear more than once. A list can mix types, but in practice its items are usually all of one kind, such as all strings or all numbers.
The function len, which comes with Python just like print, gives back the length of a list: how many items it holds. A pair of brackets with nothing between them, [], is an empty list, and its length is 0.
Reaching one item by its index
Each item of a list sits at a numbered position called its index. Python counts positions from zero: the first item has index 0, the second index 1, and so on. A good way to think of an index is as "how many steps from the start", and the first item is zero steps away.
- Paris
- Rome
- Oslo
To read one item, write the name of the list followed by the index in square brackets:
cities = ["Paris", "Rome", "Oslo"]
print(cities[0]) # Paris, the first item
print(cities[2]) # Oslo, the last item
print(cities[-1]) # Oslo again: -1 counts from the endBecause counting starts at zero, a list of 3 items has the indexes 0, 1 and 2. The last index is always one less than the length, len(cities) - 1. Python also accepts negative indexes, which count from the end: -1 is the last item and -2 the one before it.
True or false?
In a list of 4 items, the last item is at index 4.
False. The indexes are 0, 1, 2 and 3. The last index is the length minus one.
For any list that is not empty, writing [0] after its name gives its first item.
True. Counting starts at zero, so the first item is zero steps from the start.
An index past the end
Asking for a position the list does not have is an error. With three cities, cities[3] asks for a fourth item that does not exist, and Python stops the program. The last line of its error message names the kind of error and what happened:
IndexError: list index out of rangeThis is one of the most common errors with lists, and it almost always comes from counting from one instead of from zero, as in cities[len(cities)], which points one step past the last item. The lines above the error message show the file name and the line number, so you can go straight to the index that was too big.
Running the same code for every item
Reading items one index at a time works for a few items, but a list may hold three items today and three hundred tomorrow. A for loop solves this: it runs a block of code once for every item of a list, in the order the items appear, however many there are.
cities = ["Paris", "Rome", "Oslo"]
for city in cities:
print(f"I would like to visit {city}.")
print("Done.")I would like to visit Paris.
I would like to visit Rome.
I would like to visit Oslo.
Done.The first line reads almost like English: for each city in cities. It is built from these pieces:
forstarts the loop.cityis a name you choose for the current item. Before each round, Python assigns the next item to it, exactly like an assignment with=.in citiessays which list to walk through.- The colon ends the line, and the indented lines under it are the block that runs in every round, as with
ifandwhile.
The first line that is no longer indented, here print("Done."), is outside the loop and runs once, after the last round.
- city = "Paris" run the block
- city = "Rome" run the block
- city = "Oslo" run the block
- no items left go on after the loop
- city = "Paris" to city = "Rome"
- city = "Rome" to city = "Oslo"
- city = "Oslo" to no items left
Compare this with a while loop, which repeats as long as a condition stays True and needs you to update a counter yourself. A for loop needs no counter and no index: it hands you the items themselves, one after another, and it stops by itself when the list runs out. It cannot run forever over a list that does not grow.
Name the current item with a singular word that says what one item is: for city in cities, for score in scores. The plural name for the list and the singular name for one item make the line easy to read.
Everything you already know works inside the block, including if. So does break: it leaves a for loop at once, just as it leaves a while loop.
Two details follow from the way the name is assigned. A loop over an empty list runs its block zero times, because there is no item to assign. And after the loop has finished, the name still exists and refers to the last item.
True or false?
A for loop over a list of 5 items runs its block 5 times.
True. The block runs once for every item, so the number of rounds is the length of the list.
To walk through a list with a for loop, you first need a counter that holds the current index.
False. The for loop assigns each item to the loop name for you, in order. No index is needed.
A for loop over an empty list runs its block once, with nothing in the loop name.
False. With no items there is nothing to assign, so the block runs zero times and the program goes on after the loop.
Cutting a string into a list with split
Text often holds several values in one line, kept apart by a chosen character. That character is called a separator. In "Paris|France" the separator is a vertical bar, and it keeps the city apart from the country.
The string method split cuts a string at every separator and gives back a list of the parts between them. The separator itself is left out of the parts:
line = "Paris|France"
parts = line.split("|")
print(parts)
print(parts[0])
print(line)['Paris', 'France']
Paris
Paris|FranceAs with the other string methods, split does not change the string: line is still the same text afterwards, and the parts arrive in a new list. A string with two separators gives three parts, and in general the number of parts is one more than the number of separators.
Splitting with a separator cuts exactly at that character and nowhere else. It does not remove spaces, so "Paris | France".split("|") gives ['Paris ', ' France'], with a space left at the end of the first part and at the start of the second. Call .strip() on a part when you need it tidy.
Every separator makes a cut, even when nothing stands next to it. So two separators side by side, or one at the very end, give an empty string as a part: "1,,2".split(",") gives ['1', '', '2'].
Called with nothing between the brackets, split() works differently: it cuts at spaces, treats a run of several spaces as one, and leaves no empty parts. "the quick fox".split() gives ['the', 'quick', 'fox'].
True or false?
After parts = line.split(","), the string line is still exactly the same text.
True. split gives back a new list of parts and leaves the string as it was.
The string "red, green".split(",") gives the list ['red', 'green'].
False. Only the comma is removed. The space after it stays, so the second part is ' green'.
One name for each part
When you know how many parts a line has, you can give each part its own name in a single assignment. Put the names on the left of =, separated by commas:
city, country = "Paris|France".split("|")
print(city) # Paris
print(country) # FrancePython assigns the items of the list to the names in order: the first part to the first name, the second part to the second name. This is called unpacking. It needs exactly as many names as there are parts, and Python never drops or invents a part to make them fit. If the counts differ, the program stops with an error whose last line says which way they differ:
| line | What happens |
|---|---|
| "Paris|France" | city is Paris, country is France |
| "Paris|France|Europe" | ValueError: too many values to unpack (expected 2, got 3) |
| "Paris" | ValueError: not enough values to unpack (expected 2, got 1) |
Splitting and unpacking together turn one line of text into named values in a single step, and a for loop can do that for every line of a list.
lines = ["Paris|France", "Rome|Italy", "Oslo|Norway"]
for line in lines:
city, country = line.split("|")
print(f"{city} is in {country}.")Paris is in France.
Rome is in Italy.
Oslo is in Norway.True or false?
If a line splits into three parts but only two names stand on the left, Python keeps the first two parts and drops the third.
False. Unpacking needs exactly one name per part. With three parts and two names, Python raises ValueError: too many values to unpack.
In first, second = "a-b".split("-"), the name first refers to the string 'a'.
True. The parts are assigned to the names in order, so first gets 'a' and second gets 'b'.