Python Basics: Understanding Assignment, Shallow Copy, and Deep Copy for Strings and Lists
This note explains how Python variable assignment creates references, demonstrates the differences between shallow and deep copying of lists, and provides concrete code examples showing how modifications affect original and copied objects for both one‑dimensional and multi‑dimensional lists.
Assignment in Python is just creating a new reference (alias) to the same object.
Example:
list1 = [12,31,4,5565,34]
list2 = list1
print(list1)
print(list2)
list1[2] = "哈哈"
print(list1)
print(list2)The output shows both list1 and list2 reflect the change because they refer to the same list.
To avoid this, a shallow copy can be used for one‑dimensional lists.
import copy
list3 = [23,45,6,78,93,42]
list4 = list3.copy()
print(list3, list4)
list3[3] = "呵呵"
print(list3)
print(list4)The output shows list4 remains unchanged, confirming that shallow copy creates a new list object with the same elements.
For multi‑dimensional lists, shallow copy is insufficient; a deep copy is needed.
list5 = [23,43,[45,52,47],98,94]
import copy
list6 = copy.deepcopy(list5)
print(list5, list6)
list5[2][1] = "张三"
print(list5)
print(list6)The output demonstrates that modifications to nested elements affect only the original list, while the deep‑copied list stays unchanged.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
