bhylu.com

Advertisements

Copy Lists

Copying a list creates a new outer container. It does not automatically duplicate nested mutable objects.

Understand the idea

A slice or copy method is a shallow copy. That is enough for a list of immutable strings, but nested lists remain shared. deepcopy can copy a larger object graph when that is genuinely the desired contract. Avoid choosing it automatically for objects with external resources or important shared identity.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

original = [["pen"], ["pad"]]
copied = original.copy()
copied[0].append("eraser")
print(original)

Read the result

The original's first nested list now contains pen and eraser because the inner list was shared.

Try one change

Replace copied[0] with a new list and compare that with appending inside the shared nested list.