[Tutor] Nested list item assignment

Joseph J. Strout joe@strout.net
Wed, 25 Aug 1999 16:26:05 -0700


At 1:04 AM +0200 08/26/99, Tore Ericsson wrote:

>Can anybody explain line 6 in this:
>
> >>> A = [[0]*3]*3
> >>> A
>[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
> >>> A[0][0] = 1
> >>> A
>[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
> >>> # One assigned, three updated!?

You have to watch out for lists; being mutable objects, if A is a 
list, and you do B=A, then A and B refer to the *same* list, and 
changing one immediately appears to change the other.

You've run into the same here; your list contains three references to 
the *same* sub-list.

Probably you want to use Numeric.array for this sort of thing anyway, 
or at least the built-in array module.  Otherwise, try:

	A = map(lambda x:[0]*3, range(3))

which is considerably more cryptic, but does get you a list of three 
unique sub-lists.  If anybody can suggest a clearer way to accomplish 
this, I'd like to hear it too!

Cheers,
-- Joe

,------------------------------------------------------------------.
|    Joseph J. Strout           Biocomputing -- The Salk Institute |
|    joe@strout.net             http://www.strout.net              |
`------------------------------------------------------------------'