…
…
Python Programming Fundamentals · Lesson 25 / 40 · Lists
PreviewIn this lesson you will
is, and fix it with copy(), [:], or list()You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Before changing a customer's cart, Ada wrote backup = cart to keep a backup and added water to the backup; water also appeared in the original cart. Her price increase function also returns the raised list correctly, but it raises the original menu too, and there is no error message anywhere. In this lesson you will catch and fix this sneaky bug, and you will keep the weekly sales as a row-and-column table.
At the end of the lesson you will fix the price increase function so that it returns a new, raised list without touching the original menu. The fixed program will print this:
Outputmenu: [4.25, 2.0, 1.25]
raised: [4.5, 2.25, 1.5]Most of the errors you have met so far announced themselves: a red error message, a line number, an error type. The bug in this lesson is not like that. The program runs to the end and even the result looks right, but a list you thought you had not touched has silently changed. To find this kind of bug you need to know how Python names lists. Once you understand it, both the diagnosis and the fix take one line.
In this lesson you will:
is.Why do you need this? Taking a backup of a list before changing it is a very natural wish: if the customer changes their mind, you want to go back to the old state. But if you take the backup the wrong way, you do not get a backup; you get a second name for the same list.
In lesson 2 we said a variable is a name given to a value: an assignment binds the value on the right to the name on the left. This definition has an important consequence for lists. When you write backup = cart, Python does not make a new list; it gives a second name to the list that already exists. This is called aliasing. Because a list can be changed in place, backup.append("water") changes that single list, and the change is visible from both names.
Example 1 (case): The "backup" that is not a backup
cart = ["latte", "tea"] backup = cart backup.append("water") print(cart) print(backup is cart)
Output['latte', 'tea', 'water']
TrueWe never touched cart, but it has water in it. The is on the last line asks whether the two names point to the same list; you saw it as is None in lesson 8. The answer True tells you there is only one list.
Predict without running: how many items does cart hold in the code below?
What does this code print?
cart = ["latte", "tea"] backup = cart backup.append("water") print(len(cart))
Now follow the same situation step by step. This code has three names: a, b, and c. b = a is a second key; c = a.copy() is a new list (we will see copying in detail in the next section). While line 4 runs, watch the variable boxes: a and b change together, and c stays where it is.
Run the code line by line: see which line runs next, the variable boxes and the output.
a = ["tea", "latte"] b = a c = a.copy() b.append("cookie") print(a) print(c)
Does the same thing happen with numbers and strings? It does not, and the reason matters. Numbers and strings are immutable values: you cannot turn the number 3 into 4 in place. When you write backup = count, two names point to the same value again; but backup += 1 does not change that value, it produces a new number (4) and binds the name backup to it. count stays on the old number, 3. Lists can be changed in place, so operations like append, remove, or items[i] = x change that single list, and every name sees it. In short, the problem is not "two names"; it is the combination of "two names + changing in place".
What does this code print?
count = 3
backup = count
backup += 1
print(count, backup)Why do you need this? When you want to protect the original list, you do not need a second key, you need a second house: a separate list with the same items. Python offers three equivalent ways for this, and all three do the same job.
| Line | Is a new list created? | When one changes, does the other? |
|---|---|---|
b = a | No | It changes |
b = a.copy() | Yes | It does not change |
b = a[:] | Yes | It does not change |
b = list(a) | Yes | It does not change |
copy() is a method of the list, and because its name says what it does, it is the most readable one. a[:] is the slice you saw in lesson 20: a slice with an empty start and end takes the whole list into a new list. list(a) builds a new list from what you give it, like the type conversions in lesson 4. Which one you choose is a matter of taste; in this lesson we mostly use copy().
Example 2 (case): Three ways to copy
cart = ["latte", "tea"] c1 = cart.copy() c2 = cart[:] c3 = list(cart) c1.append("water") print(cart, c1) print(c2 == cart, c2 is cart)
Output['latte', 'tea'] ['latte', 'tea', 'water']
True FalseWater was added to c1, and cart stayed exactly the same: the copy is independent. The last line asks two questions side by side. == asks "are the values equal?": c2 and cart hold the same items, so the answer is True. is asks "is it the same list?": c2 is a separate list, so the answer is False. Two lists with the same values are like twins: they look exactly alike, but when one gets a haircut, the other does not change. So you cannot conclude from a == b being true that the two are the same list.
Match each line with its meaning below. One option was added as a distractor; no line in this lesson does exactly that.
Choose what each line does.
For each row, pick its match from the list, then check.
b = ab = a.copy()b = a[:]b = list(a)a == ba is bWhy do you need this? The add_to_cart(cart, item) you wrote in lesson 23 changed the cart even though it returned nothing; we left the reason for later. The reason is now clear: when you call a function, the parameter is a new name given to the list outside. It is not a copy. If you do append, remove, or items[i] = x inside the function, you change the list outside.
Sometimes this is exactly what you want: the purpose of add_to_cart is to put the item into the original cart. Sometimes it is a big mistake. Ada's price increase function was written to "calculate the raised prices"; it was not supposed to change the original menu. Let's see what happens.
Example 3 (case): The price increase function breaks the original menu
def raise_prices(prices, amount): for i in range(len(prices)): prices[i] = prices[i] + amount return prices menu = [4.25, 2.00, 1.25] new = raise_prices(menu, 0.25) print("menu:", menu) print("new:", new)
Outputmenu: [4.5, 2.25, 1.5]
new: [4.5, 2.25, 1.5]prices and menu are two names of the same list. As the loop changed prices[i], the original menu changed too; and return prices gave back not a new list but the same list. So menu, prices, and new are three names, one list. The fix is one line: take a copy before the function starts its work and work on the copy all the time.
Example 3, fixed: the target program of the lesson
def raise_prices(prices, amount): # 1. Protect the original list: work on a copy raised = prices.copy() # 2. Add the increase to every price in the copy for i in range(len(raised)): raised[i] = raised[i] + amount # 3. Return the copy return raised menu = [4.25, 2.00, 1.25] raised = raise_prices(menu, 0.25) print("menu:", menu) print("raised:", raised)
Outputmenu: [4.25, 2.0, 1.25]
raised: [4.5, 2.25, 1.5]See the difference yourself. In the code below, the variable make_copy switches the first line of the function on and off. Try both values and look at the answer to "Same list?" on the last line.
Change the value of make_copy: is the original menu protected?
Pick a value; predict the output first, then look.
1make_copy = False23def raise_prices(prices, amount):4 if make_copy:5 prices = prices.copy()6 for i in range(len(prices)):7 prices[i] = prices[i] + amount8 return prices910menu = [4.25, 2.00, 1.25]11new = raise_prices(menu, 0.25)12print("menu:", menu)13print("new:", new)14print("Same list?", new is menu)
menu: [4.5, 2.25, 1.5] new: [4.5, 2.25, 1.5] Same list? True
Faded lines didn't run with this value. When it is False, prices is a second name for the outside menu; the loop changes the original menu, and the returned list is the same list. When it is True, the first line binds the name prices to a new copy; the loop changes the copy, and menu stays as it was.
The rule can be summed up like this: if the function's job is "return a new list", copy first. If its job is "update the list you were given" (like add_to_cart), do not copy; then you usually do not need to return anything either.
There is one more trap that comes from the same cause. In lesson 15 you learned to give a parameter a default value (quantity=1). When the default value is a list, something surprising happens:
def add(item, cart=[]): cart.append(item) return cart print(add("latte")) print(add("tea"))
Output['latte']
['latte', 'tea']The second customer only wanted tea, but their cart also has the first customer's latte. Written with cart=None, the two calls return ['latte'] and ['tea'].
Why do you need this? Ada wants to keep the daily sales of every product: three products, three days. Instead of nine separate variables or three separate lists, you need a single structure. A list can hold values of any type, so it can also hold other lists. A list whose items are lists is called a nested list, and it is the simplest way to hold data in the form of a table: each inner list is one row of the table.
sales = [
[12, 15, 9],
[20, 18, 25],
[7, 10, 8],
]| Mon (column 0) | Tue (column 1) | Wed (column 2) | |
|---|---|---|---|
| Latte (row 0) | 12 | 15 | 9 |
| Tea (row 1) | 20 | 18 | 25 |
| Cookie (row 2) | 7 | 10 | 8 |
You reach a cell with two indexes: first the row, then the column. sales[1] gives the whole second row, that is, the three-day list of tea. sales[1][2] gives the third item of that list, Wednesday's tea sales. When you read it, go from left to right: first sales[1] produces a list, then [2] is applied to that list. Cells can be updated like variables: sales[0][1] += 1 increases Tuesday's latte sales by one.
Example 4 (case): A cell, a row, and totals
sales = [[12, 15, 9], [20, 18, 25], [7, 10, 8]] print(sales[1]) print(sales[1][2]) sales[0][1] += 1 print(sales[0], sum(sales[0]))
Output[20, 18, 25]
25
[12, 16, 9] 37You can walk through the table in two directions. Walking row by row is easy: for row in sales: gives one inner list per turn, and sum(row) is the weekly total of that product. If you keep the product names in a separate list, you pair each name with its own row using zip(products, sales) from lesson 24. Walking column by column, that is, finding the total of each day, takes a little more thought: there is no separate list called a "column" in the table. So the outer loop goes over the column index (j), and the inner loop takes the number in that column from all the rows. This is exactly the nested loop from lesson 13.
Example 4, continued: Product and day totals
products = ["latte", "tea", "cookie"] days = ["Mon", "Tue", "Wed"] sales = [[12, 15, 9], [20, 18, 25], [7, 10, 8]] for product, row in zip(products, sales): print(f"{product}: {sum(row)}") for j in range(len(days)): total = 0 for row in sales: total += row[j] print(days[j], total)
Outputlatte: 36
tea: 63
cookie: 25
Mon 39
Tue 43
Wed 42Your turn. In the cell below, the table and the product total loop are ready; do the three tasks in the comment in order.
Try it now· not graded; doesn't affect progress
The most common mistake in the day total loop is putting the total = 0 line in the wrong place. Put the lines in the right order and indentation.
Put the lines of the loop that prints the total of each day in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Why do you need this? We wrote the sales table by hand. But when you want to build a seating plan with 10 tables or a cinema hall with 3 rows, you do not want to write the rows one by one. The first way that comes to mind is to repeat with *. Multiplying a list by an integer repeats its items that many times: [0] * 4 gives the list [0, 0, 0, 0] with four zeros, and ["empty"] * 2 gives ['empty', 'empty']. So does [[0] * 4] * 3 give a table with three rows?
What does this code print?
table = [[0] * 3] * 2
table[0][0] = 5
print(table)With a one-level list, * n is safe, because the items are numbers and numbers cannot be changed in place. In a nested list, the thing being repeated is a list, so all the rows become aliases of the same list. The safe way is to add a new row on each turn of a loop: the expression [0] * 4 runs again on every turn inside the loop and builds a separate list each time.
Example 5 (outside the case): One seat in a cinema hall
# 0 empty, 1 taken. Wrong setup: three rows are the same list hall = [[0] * 4] * 3 hall[1][2] = 1 for seat_row in hall: print(seat_row) print("---") # Right setup: each row is a separate list hall = [] for i in range(3): hall.append([0] * 4) hall[1][2] = 1 for seat_row in hall: print(seat_row)
Output[0, 0, 1, 0]
[0, 0, 1, 0]
[0, 0, 1, 0]
---
[0, 0, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 0]In the wrong setup, only the third seat of the middle row was reserved, but the whole column looks taken; the box office cannot sell two more tickets for this hall. In the right setup, only that one seat is taken.
The same detail shows up in copying too. copy(), [:], and list() copy only the outer list: a new outer list is built, but the old rows themselves are put inside it. This is called a shallow copy. Adding a row to the copy or deleting a row from it does not affect the original table; but changing a cell in the copy also changes the same cell in the original table, because that row is shared by the two tables.
Example 6 (case): A shallow copy of the sales table
sales = [[12, 15], [20, 18]] backup = sales.copy() backup[0][0] = 99 backup.append([1, 1]) print(sales) print(len(sales), len(backup))
Output[[99, 15], [20, 18]]
2 3The added row is only in backup (the lengths are 2 and 3), but the cell change passed to the original table too. For a fully independent copy of the table, you copy each row separately: open an empty list and add row.copy() in a loop (Example 7 below). Python also offers the copy.deepcopy function, which does this in one call; you will see modules in lesson 36.
The root of all the problems you saw in this lesson is the same: two names, one list. The symptom of this bug is not an error message, it is the feeling that "a list I did not touch changed." In such a case, apply the tracing method from lesson 18:
1. Find which names point to the list that changed: an assignment like backup = cart, a function parameter, rows repeated with * n, or a shallow copy.
2. For the two names you suspect, write print(a is b). If you see True, the two are the same list.
3. Take the copy before the place where you need to change: new = items.copy() on the first line of the function, and in a table, build each row separately or copy each row separately.
These three steps find almost all silent list bugs in a few minutes.
At the start of the day, Ada takes a backup of the sales table; while the original table is updated during the day, the backup must not be spoiled. A shallow copy is not enough; each row must be copied separately.
sales = [[12, 15, 9], [20, 18, 25]] backup = [] for row in sales: backup.append(row.copy()) sales[0][0] = 99 print(sales) print(backup) print(sales[0] is backup[0])
Output[[99, 15, 9], [20, 18, 25]]
[[12, 15, 9], [20, 18, 25]]
FalseA teacher keeps the two exam grades of three students in a table. The student is evaluated with the row average, and the exam with the column average. Since the table does not change, no copy is needed; it is only read.
names = ["Zara", "Mateo", "Lena"] grades = [[70, 80], [55, 65], [90, 100]] for name, row in zip(names, grades): print(name, sum(row) / len(row)) for j in range(2): total = 0 for row in grades: total += row[j] print(f"Exam {j + 1} average:", round(total / (grades), 1))
Thinking an assignment takes a copy. When you write backup = cart and change backup, cart changes too; no error message appears, and the problem is often noticed much later, on another line. The same happens with a function parameter: if you change a list you passed to a function inside it, the list outside changes. To diagnose it, write print(backup is cart); if you see True, there is one list. The right way: when you want an independent list, write backup = cart.copy() (or cart[:], list(cart)); in a function that returns a new list, copy first.
b = a does not copy the list, it gives the same list a second name; a function parameter is also a second name for the list outside. is asks whether it is the same list, == asks whether the values are equal.copy(), [:], or list(); in a function that returns a new list, copy first.sales[row][column]); build the rows in a loop, not with [[0] * 3] * 2, and remember: copy() is a shallow copy, so the inner rows stay shared.Next lesson: So far we kept products in order in a list; to reach a price by the product's name instead of its position number, we will move to a structure that uses keys: the dictionary.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputZara 75.0
Mateo 60.0
Lena 95.0
Exam 1 average: 71.7
Exam 2 average: 81.7