Lesson 1 · Unit 01
Names and objects
Labels, not boxes: aliasing, defaults and copies
What you practise
- Identity against equality,
isagainst==, mutable and immutable, two names for one list, the mutable default argument, shallow and deep copies
Try a question from this lesson
Pick one
A grid of zeros with 3 rows and 2 columns, then one cell is set. What prints?
grid = [[0] * 2] * 3
grid[0][0] = 5
print(grid)Hint
How many inner lists does [[0] * 2] * 3 create?
Correct answer
[[5, 0], [5, 0], [5, 0]]
Why
[[0] * 2] * 3 builds one inner list and repeats a reference to it three times. There is one row with three labels, so the change shows up in every "row". Build each row in a loop or a comprehension to get three separate lists.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Names are labels
Assignment never copies. b = a sticks a second label on the same object.
== asks "are the values equal?". is asks "is this the very same object?".
Mutate an object through one name and every other name for it sees the change. Rebind a name and only that name moves.
a = [1, 2]
b = a # second label, same list
c = [1, 2] # a different list
print(a == c) # True
print(a is c) # False
print(a is b) # True9 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.