Two names, one list
This is one of the most important pictures in Python. A variable doesn't contain a list. It points to one.
a = [1, 2] b = a # b points to the SAME list b.append(3) print(a) # [1, 2, 3] surprise!
To get an independent copy, make a new list: a.copy() or list(a).
For a list of lists, board[0] is its first row and board[0][0] is that row's first cell. A copy of the outer list still shares its inner rows. To make independent rows, start with a new list and append a copy of each row in a for loop.
See it run
a = [1, 2] b = a b.append(3) c = a.copy() c.append(4) print(a, b, c)
Names live on the left; lists live on the right. Follow the arrows.
Practice two names, one list
Exercise 1
In the editor below, backup is supposed to be a safe copy of original, but appending "blue" to the original also changes it. Fix the backup line so backup stays ["red", "green"].
Exercise 2
In the editor below, two teams start with the same players, but each then signs someone different. Make team_b its own list so that afterwards team_a is ["Ana", "Ben", "Cy"] and team_b is ["Ana", "Ben", "Dee"].
Exercise 3
In the editor below, template is a blank 2×2 board you want to reuse. Make grid a copy where changing a cell leaves template blank.
template.copy() is not enough here: it copies the outer list, but both still share the same inner rows. Copy each row too.
Exercise 4
Predict, then verify. Read this program before running it:
a = [1, 2] b = a c = a.copy() a.append(3)
What do b and c hold at the end? Guess first, then set b_prediction and c_prediction to the two lists. Run it, press Step through your code, and compare the #numbers of a, b and c before and after the append.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.