Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python object-copying code

Practice making shallow copies, deep copies, preserving recursive structures, and replacing selected record fields.

Intermediate ~8 min read

Challenge 1

Create a shallow copy of the outer dictionary; the nested items are intentionally still shared.

python Your answer
import copy

source = {"items": ["pen"]}
shallow = 
print(shallow is source)
print(shallow["items"] is source["items"])

Press Ctrl⌘Enter to check your answer

Challenge 2

Create a copy whose nested list can be changed independently from original.

python Your answer
import copy

original = {"profile": {"roles": ["reader"]}}
independent = 
independent["profile"]["roles"].append("editor")
print(original["profile"]["roles"])
print(independent["profile"]["roles"])

Press Ctrl⌘Enter to check your answer

Challenge 3

Create a new Report with title "Final" while leaving the original title unchanged.

python Your answer
from copy import replace
from dataclasses import dataclass

@dataclass
class Report:
    title: str
    labels: list[str]

original = Report("Draft", ["core"])
revised = 
print(original.title, revised.title)
print(original.labels is revised.labels)

Press Ctrl⌘Enter to check your answer

Challenge 4

Copy the self-referential list so the new list still points to itself.

python Your answer
import copy

original = []
original.append(original)
independent = 
print(independent is original)
print(independent is independent[0])

Press Ctrl⌘Enter to check your answer