runtime

compare approaches one problem · three ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Assignment vs shallow copy vs deepcopybehaves differently

Copy a list of order lines, change the copy, and look at the original.

what differs

Assignment copies nothing. list(), .copy() and [:] copy the outer list, but the inner lists are shared, so changing copy[0][1] changes the original. deepcopy copies all the way down.

at a glance

approachuse it when
A · assignmentYou want two names for the same object (rarely what ‘copy’ means).
B · shallow copyThe items are immutable (numbers, strings, tuples), or sharing them is fine.
C · copy.deepcopyNested mutable data that the copy must be able to change independently.

Watch out: deepcopy can be slow on large structures and copies things you may want shared; copy only what you'll change.

the outputs

Each approach runs on the same input.

concepts

aliasingshallow copydeep copy

learn it

Shallow and deep copies

related comparisons

Merging dicts: update() vs {**a, **b} vs | · Default argument: [] vs None

A · assignment
B · shallow copy
C · copy.deepcopy
Compare Python Approaches · Runtime