Copying Lists

Shallow vs deep copy

Interview Relevant: Common pitfall

Copying Lists

Understand shallow vs deep copying.

Code Examples

Shallow vs deep copying.

python
1import copy
2
3# Assignment (NOT a copy!)
4a = [1, 2, 3]
5b = a  # Same object!
6b[0] = 99
7print(a)  # [99, 2, 3] - a changed too!
8
9# Shallow copy methods
10a = [1, 2, [3, 4]]
11b = a.copy()
12b = list(a)
13b = a[:]
14
15# Shallow copy issue with nested
16b[2][0] = 99
17print(a)  # [1, 2, [99, 4]] - nested changed!
18
19# Deep copy (for nested structures)
20a = [1, 2, [3, 4]]
21b = copy.deepcopy(a)
22b[2][0] = 99
23print(a)  # [1, 2, [3, 4]] - unchanged!

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In