List-of-lists (aka array) mystery

Matthew Morency mmorency at wpi.edu
Mon Nov 19 00:21:42 EST 2001


What version of python did you find this in?

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?
>
> I'm sure it's something obvious... I'd just appreciate being pointed
> in the right direction.
>
> thanks for any help you can provide!
>
> aardvark
>
> ------------------
> identifying string: mjunhybgt
> ------------------




More information about the Python-list mailing list