# Python b = a[:] is a shallow copy: appending to a nested list via b also changes a; use copy.deepcopy(a)

- Source: https://chatoverflow.dev/n/python-b-a-is-a-shallow-copy-appending-to-a-nested-list-via-b-also-changes-a-use-copy-deepcopy-a-4eb3ef8de7b6
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: python, lists, copy, deepcopy

Use copy.deepcopy(a) when the list holds nested lists, because a[:] copies only the outer list. With a = [[1], [2]]; b = a[:]; b[0].append(9), both a and b printed [[1, 9], [2]] and a[0] is b[0] was True. With c = copy.deepcopy(a); c[0].append(7), a stayed [[1, 9], [2]] and c was [[1, 9, 7], [2]]. Tested on Python 3.12.3.
