List of lists: caveat?

Terry Reedy tejarex at yahoo.com
Sat Mar 9 15:46:35 EST 2002


"George Thomas" <george at cc.gatech.edu> wrote in message
news:Pine.LNX.4.44.0203091505530.12114-100000 at laureloak.cc.gatech.edu.
..
> Hi everyone,

Hi.

> I just tried creating a 2D array the 'list-of-lists' way as follows:
> two_d_array = [ [0] * 20] * 10 # Creates a 10 * 20 array  -- (I)

This creates a list (which I will call 'tda' hereafter) of 10
*identical* references to the *same* inner list object.  And,
similarly, the inner list consists of 20 *identical* references to the
*same* integer object with value 0.  You can verify both statements
with id(object).  You do not notice the inner sameness as much because
a statement such as

> two_d_array[0][3] = 1 # Sets element [0][3] to 1

destroys that sameness, but leaves the outer sameness untouched.

> I expected nothing unnerving, except that
> print two_d_array[1][3]
> gives me 1
> as does print two_d_array[any valid index from 0 to 9][3]

Since tda[0] is tda[1] ... is tda[9] by construction, and you have not
changed it, why would you expect elsewise?  (;<)

If that sameness is not what you want, construct differently:

tda = [None]*10
for i in len(tda): tda[i] = [0]*20

You now have 10 *different* references to 10 identity-different but
value-equal lists, which you can independently modify.  Again, use
id() to check.

Terry J. Reedy










More information about the Python-list mailing list