List-of-lists (aka array) mystery

Hans Nowak wurmy at earthlink.net
Mon Nov 19 03:54:49 CET 2001


aardvark wrote:
> 
> Hi everyone
> 
> A friend of mine has discovered some interesting behavior with
> lists-of-lists (I suppose some call them "arrays"). When you define
> (or "initialize") a list-of-lists using the range() function, then set
> a value within one of the inner lists, the value of each inner list
> item in that same position becomes the new value. When you explicitly
> define (or "initialize") the list-of-lists the behavior is as
> expected, i.e. only the value in the list position you specified,
> within the list you specified, is changed.
> 
> A better way to show this is with an example:
> 
> Definition using range:
> 
> >>> x=[range(-1,0)*3]*3
> >>> x
> [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
> >>> x[1][1]=0
> >>> x
> [[-1, 0, -1], [-1, 0, -1], [-1, 0, -1]]
> 
> I did not expect x[0][1] and x[2][1] to become 0. I only expected
> x[1][1] to become 0. This does not happen when you explicitly define
> the list:
> 
> >>> x=[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
> >>> x
> [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
> >>> x[1][1]=0
> >>> x
> [[-1, -1, -1], [-1, 0, -1], [-1, -1, -1]]
> 
> Why is this? It would seem that multiplying the result of the range()
> function twice returns pointers to a single list rather than discrete
> lists. Is there a better way to initialize lists-of-lists? Should I be
> going about this differently?

It's a FAQ:

  http://www.python.org/cgi-bin/faqw.py?req=all#4.50

Note that this behavior is unrelated to range.

HTH,



More information about the Python-list mailing list