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: List repetition operator gives unexpected results
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: austin.green, steven.daprano
Priority: normal Keywords:

Created on 2020-10-31 22:11 by austin.green, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg380101 - (view) Author: Austin Green (austin.green) Date: 2020-10-31 22:11
Not sure if this is a bug, cannot find any clarification in the documentation.  Please reassign it if need be.

Using the * operator to generate a list of lists:
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
gives a list of 3 lists of zeroes, as expected.
But the data values appear to be shared, so e.g.
>>> a[1][1] = 'spam'
>>> a
[[0, 'spam', 0], [0, 'spam', 0], [0, 'spam', 0]]
Not what I was expecting!

A list comprehension gives the results I wanted:
>>> a = [[0 for x in range(3)] for x in range(3)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Looks just the same, but:
>>> a[1][1] = 'spam'
>>> a
[[0, 0, 0], [0, 'spam', 0], [0, 0, 0]]
gives a different result, and is actually what I was expecting from the first example.
msg380103 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-10-31 22:31
This is not a bug. The sequence repetition operator does not *copy* items, as explained here:

https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
msg380106 - (view) Author: Austin Green (austin.green) Date: 2020-10-31 23:09
Thanks for that; I suspected as much.  Could not find anything about it searching the web, so it's a feature not much discussed by the numerous Python tutorials.
History
Date User Action Args
2022-04-11 14:59:37adminsetgithub: 86389
2020-10-31 23:09:37austin.greensetmessages: + msg380106
2020-10-31 22:31:49steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg380103

resolution: not a bug
stage: resolved
2020-10-31 22:11:50austin.greencreate