[issue27135] nested list produced with multiplication is linked to the same list

Matthew Tanous report at bugs.python.org
Fri May 27 01:25:00 EDT 2016


New submission from Matthew Tanous:

If I produce a list in this fashion:

l = [[x] * n] * n

I would expect that I would obtain a matrix-like structure.  Instead, I get a list of the *same* list, such that the statement:

l[x][y] = z

would change, in essence, every value in "column" y.  This is different from the case where the list contains a string or integer value, where the new list points to separate instances of the internal values.

In my view, this is strange and counter-intuitive behavior.  If I want to create a matrix-like set to None to start, instead of using:

 mat = [[None] * N] * N

I have to use:

 mat = [[None] * N for i in range(N)]

If there is any possibility for it to be changed, I think that would improve things considerably.  In almost no cases, in my opinion, would I want a list of lists that are forced to be the same.

----------
components: Interpreter Core
messages: 266475
nosy: Matthew Tanous
priority: normal
severity: normal
status: open
title: nested list produced with multiplication is linked to the same list
versions: Python 2.7, Python 3.5

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue27135>
_______________________________________


More information about the Python-bugs-list mailing list