New submission from Austin Green <austin.gr...@orcon.net.nz>:

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.

----------
components: Interpreter Core
messages: 380101
nosy: austin.green
priority: normal
severity: normal
status: open
title: List repetition operator gives unexpected results
type: behavior
versions: Python 3.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42223>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to