Practice: copy and deepcopy

« Read the chapter

Q1. Make a list copy

BeginnerCoding

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

IntermediateCoding

Deep copy [[1, 2], [3, 4]], change the copy's first value to 99, and print the original.

Goal: Use deepcopy.

Q3. Check identity

BeginnerCoding

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

IntermediateCoding

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

IntermediateCoding

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

BeginnerOutput

What does this print?

Code
a = [1, 2]
b = a
b[0] = 100
print(a)

Goal: Aliases.

Q7. Shallow nested

IntermediateOutput

What does this print?

Code
import copy
a = [[1], [2]]
b = copy.copy(a)
b[0].append(5)
print(a)

Goal: Shallow trap.

Q8. Deep nested

IntermediateOutput

What does this print?

Code
import copy
a = [[1], [2]]
b = copy.deepcopy(a)
b[0].append(5)
print(a, b)

Goal: Deep copy.

Q9. Repeated rows

IntermediateOutput

What does this print?

Code
g = [[0] * 2] * 2
g[0][0] = 7
print(g)

Goal: Shared rows.

Q10. Equality vs identity

IntermediateOutput

What does this print?

Code
import copy
a = [1, 2]
b = copy.copy(a)
print(a == b, a is b)

Goal: == and is.

Q11. Memo keeps sharing

AdvancedOutput

What does this print?

Code
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

IntermediateDebugging

This code changes the original dictionary's inner list. Fix it so the original keeps ['x'].

Code
import copy
orig = {'tags': ['x']}
new = copy.copy(orig)
new['tags'].append('y')
print(orig['tags'])

Goal: Deep vs shallow.

Q13. Fix the backup

BeginnerDebugging

This code was meant to keep a backup but the backup also changes. Fix it.

Code
nums = [1, 2, 3]
backup = nums
nums.append(4)
print(backup)

Goal: Alias bug.

Q14. Shallow or deep

BeginnerConceptual

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

AdvancedConceptual

What is the memo dictionary in deepcopy used for?

Goal: deepcopy internals.

Q16. Undo move

IntermediateApplication

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

AdvancedApplication

Make two student records from the template {'name': '', 'marks': []} using deepcopy. Add mark 5 to the first only. Print both.

Goal: Templates.