List of lists: caveat?
tejarex at yahoo.com
Sat Mar 9 21:46:35 CET 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,
> I just tried creating a 2D array the 'list-of-lists' way as follows:
> two_d_array = [  * 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 = 1 # Sets element  to 1
destroys that sameness, but leaves the outer sameness untouched.
> I expected nothing unnerving, except that
> print two_d_array
> gives me 1
> as does print two_d_array[any valid index from 0 to 9]
Since tda is tda ... is tda 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] = *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