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
| approach | use it when |
|---|---|
| A · assignment | You want two names for the same object (rarely what ‘copy’ means). |
| B · shallow copy | The items are immutable (numbers, strings, tuples), or sharing them is fine. |
| C · copy.deepcopy | Nested 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
related comparisons
Merging dicts: update() vs {**a, **b} vs | · Default argument: [] vs None