[Python-bugs-list] Problem with multi-dimensional arrays (PR#94)

guido@CNRI.Reston.VA.US guido@CNRI.Reston.VA.US
Mon, 4 Oct 1999 16:42:02 -0400 (EDT)


> When I do an assignment of the form "array[i][j]=k", every element in
> column j gets set to k:
> 
> Python 1.5.2 (#3, Sep 22 1999, 16:32:41)  [GCC egcs-2.91.66 19990314/Linux
> (egcs- on linux2
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> foo = [ [1] * 4 ] * 4
> >>> foo
> [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
> >>> foo[3]
> [1, 1, 1, 1]
> >>> foo[3][2]
> 1
> >>> foo[3][2]=5
> >>> foo
> [[1, 1, 5, 1], [1, 1, 5, 1], [1, 1, 5, 1], [1, 1, 5, 1]]
> >>> foo[1][2]
> 5

This is not a bug; the expression [ [1]*4 ] * 4 yields a list with
four references to the same object (each of which in turn is a list of
four references to the number 1).

A solution in this case would be:

  >>> foo = []
  >>> for i in range(4):
  ...     foo.append([1]*4)
  ...
  >>> 

But it is important to have a thourough understanding of this issue
before getting further entangled.  Ask the Python newsgroup
comp.lang.python or write to help@python.org for more help on this
issue.  It is also dealt with in the book Learning PYthon.

--Guido van Rossum (home page: http://www.python.org/~guido/)