List-of-lists (aka array) mystery

Jeff Shannon jeff at ccvcorp.com
Mon Nov 19 21:12:04 EST 2001


aardvark wrote:

> Hi everyone
>

[snip discussion of list-of-list behaviors]

>
> 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.

This is, indeed, exactly the case, and is deliberate behavior.  It has
nothing to do with range(), either, and your example would work exactly
the same if you replaced your range(-1,0) with a simple [-1].  It's just
the way that multiplication works on lists -- '[object] * n' creates a
list of n references to object, not n copies of object.  The distinction
is minimal, though, unless object is mutable (like, say, a list, dict, or
class instance).

> Is there a better way to initialize lists-of-lists? Should I be
> going about this differently?

Two possibilities--

x = []
for i in range(3):
    x.append( [-1] * 3)

x = [ [ inner] * 3 for inner in ( [-1] * 3)]

These both work by constructing a separate (though equal) inner list each
time.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list