Exercises
Copy Lists
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Make b a real copy, so appending to it leaves a alone.
Python
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)copy() says what it means.
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)Exercise 2Passed
A shallow copy is not enough here. Copy the grid so changing the inner list leaves the original alone.
Python
grid = [[1, 2], [3, 4]]
copy_of_grid = grid.copy()
copy_of_grid[0].append(99)
print(grid)copy has a deepcopy function.
from copy import deepcopy
grid = [[1, 2], [3, 4]]
copy_of_grid = deepcopy(grid)
copy_of_grid[0].append(99)
print(grid)Exercise 3Passed
Build a discounted list at 90% of each price, leaving prices alone.
Python
prices = [10, 20, 30]
# build discounted
print(prices)
print(discounted)A comprehension makes a new list without any copying.
prices = [10, 20, 30]
discounted = [p * 0.9 for p in prices]
print(prices)
print(discounted)