This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Shallow copy occurs when list multiplication is used to create nested lists; can confuse users
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ohwphil, steven.daprano
Priority: normal Keywords:

Created on 2021-09-11 02:55 by ohwphil, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg401625 - (view) Author: 2106 Hyunwoo Oh (ohwphil) Date: 2021-09-11 02:55
If you do the following:

lists=[[]]*100
lists[1].append('text')
print(lists[2])

you can see lists[2] contains 'text' even though it was appended to lists[1] in the text. A little more investigation with the id() function can show that the lists are shallowly copied when list multiplication occurs. I think this can confuse users when they try to use list multiplication to create nested lists, as they expected a deep copy to occur.
msg401626 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-09-11 03:07
This is not a bug. No copy is made at all, neither shallow nor deep.

This is described in the documentation for built-in types:

https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

and is similar to the issue in the FAQs:

https://docs.python.org/3/faq/programming.html#id16


I acknowledge that this is sometimes confusing for beginners, but it is just one of those things that programmers have to learn. Sequence multiplication does not copy the items, it replicates references to the same item.
msg401627 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-09-11 03:09
Oh, I forgot: this exact issue is also in the FAQs.

https://docs.python.org/3/faq/programming.html#id46
History
Date User Action Args
2022-04-11 14:59:49adminsetgithub: 89332
2021-09-11 03:09:16steven.dapranosetmessages: + msg401627
2021-09-11 03:07:46steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg401626

resolution: not a bug
stage: resolved
2021-09-11 03:00:08ohwphilsetcomponents: + Interpreter Core, - Demos and Tools
2021-09-11 02:55:07ohwphilcreate