Practice: copy and deepcopy
Q1. Make a list copy
Make a copy of [1, 2, 3] called b, append 4 to b, and print both lists.
Goal: Shallow copy.
Q2. Deep copy a matrix
Deep copy [[1, 2], [3, 4]], change the copy's first value to 99, and print the original.
Goal: Use deepcopy.
Q3. Check identity
Create a = [1] and b = a. Print whether a is b, then whether a is a copy of itself made with list(a).
Goal: Identity.
Q4. Safe settings
Write a function that gets a dict, deep copies it, adds 'debug': True to the copy and returns it. Print the original after calling it with {'a': [1]}.
Goal: Protect data.
Q5. Correct grid
Create a 2x3 grid of zeros so that changing grid[0][0] to 1 does not change grid[1][0]. Print the grid after the change.
Goal: Avoid shared rows.
Q6. Alias effect
What does this print?
a = [1, 2]
b = a
b[0] = 100
print(a)Goal: Aliases.
Q7. Shallow nested
What does this print?
import copy
a = [[1], [2]]
b = copy.copy(a)
b[0].append(5)
print(a)Goal: Shallow trap.
Q8. Deep nested
What does this print?
import copy
a = [[1], [2]]
b = copy.deepcopy(a)
b[0].append(5)
print(a, b)Goal: Deep copy.
Q9. Repeated rows
What does this print?
g = [[0] * 2] * 2
g[0][0] = 7
print(g)Goal: Shared rows.
Q10. Equality vs identity
What does this print?
import copy
a = [1, 2]
b = copy.copy(a)
print(a == b, a is b)Goal: == and is.
Q11. Memo keeps sharing
What does this print?
import copy
x = [1]
data = [x, x]
copy_data = copy.deepcopy(data)
copy_data[0].append(2)
print(copy_data)Goal: deepcopy memo.
Q12. Fix the shared change
This code changes the original dictionary's inner list. Fix it so the original keeps ['x'].
import copy
orig = {'tags': ['x']}
new = copy.copy(orig)
new['tags'].append('y')
print(orig['tags'])Goal: Deep vs shallow.
Q13. Fix the backup
This code was meant to keep a backup but the backup also changes. Fix it.
nums = [1, 2, 3]
backup = nums
nums.append(4)
print(backup)Goal: Alias bug.
Q14. Shallow or deep
A list holds only integers. Is a shallow copy enough to keep the original safe? Explain.
Goal: Choose copy type.
Q15. What is a memo
What is the memo dictionary in deepcopy used for?
Goal: deepcopy internals.
Q16. Undo move
Keep a board [[1, 2], [3, 4]]. Save a deep copy as saved, change board[0][0] to 0, then restore by setting board = saved. Print board.
Goal: Undo with deepcopy.
Q17. Template record
Make two student records from the template {'name': '', 'marks': []} using deepcopy. Add mark 5 to the first only. Print both.
Goal: Templates.