Assignment vs Shallow Copy vs Deep Copy in Python: Key Differences
assignment just creates a new reference to the same object, so changes affect both. Shallow copy copies the object but not nested objects, so inner changes affect both. Deep copy copies everything recursively, making fully independent objects.Quick Comparison
Here is a quick table to compare assignment, shallow copy, and deep copy in Python based on key factors.
| Factor | Assignment | Shallow Copy | Deep Copy |
|---|---|---|---|
| Creates new object? | No, same object referenced | Yes, new outer object | Yes, new object and nested objects |
| Copies nested objects? | No | No, nested objects shared | Yes, all nested objects copied |
| Changes affect original? | Yes, always | Yes, if nested objects changed | No, fully independent |
| Use case | Simple reference | Copy with shared nested data | Complete independent copy |
| Performance | Fastest | Moderate | Slowest |
Key Differences
Assignment in Python means giving a new name to the same object. No new object is created, so if you change the object through one name, the change shows up through the other name too.
Shallow copy creates a new outer object but does not copy nested objects inside it. Instead, it copies references to those nested objects. So if you change a nested object, both copies see the change.
Deep copy creates a new object and recursively copies all nested objects inside it. This means the new copy is fully independent, and changes to nested objects in one copy do not affect the other.
Code Comparison
Here is an example showing assignment behavior with a nested list.
original = [[1, 2], [3, 4]] assigned = original assigned[0][0] = 99 print("Original after assignment change:", original)
Shallow Copy Equivalent
Here is how shallow copy works on the same nested list example.
import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) shallow[0][0] = 99 print("Original after shallow copy change:", original)
Deep Copy Equivalent
Here is how deep copy works on the same nested list example.
import copy original = [[1, 2], [3, 4]] deep = copy.deepcopy(original) deep[0][0] = 99 print("Original after deep copy change:", original) print("Deep copy after change:", deep)
When to Use Which
Choose assignment when you want multiple names for the same object and want changes to reflect everywhere.
Choose shallow copy when you want a new outer object but are okay with nested objects being shared and reflecting changes.
Choose deep copy when you need a fully independent copy with no shared nested objects, even if it costs more time and memory.