[Tutor] Nested list anomaly

Lloyd Kvam pythontutor@venix.com
Tue, 30 Apr 2002 08:28:45 -0400


I have to confess that I still get burned by unexpectedly creating lists
with multiple references.  Is there a simple rule of thumb for recognizing
when you have simply created multiple references?

[[0]*2]*3 
multiple references
[[0]*2 for i in range(3)]	multiple lists

On casual inspection these seem awfully similar.

dman wrote:

> On Tue, Apr 30, 2002 at 10:07:32AM +1000, Hugh Stewart wrote:
> 
> | Test 1:
> | >>> c1 = [[0]*2]*3
> | >>> c1
> | [[0, 0], [0, 0], [0, 0]]
> 
> This looks good, but what you have is a 3-element list where all
> elements are identical references to the same 2-element list.  Since
> lists are mutable, if you change the list, the change is seen by all
> the references to it.
> 
> | Test 2:
> | >>> c2 = [[0,0]]*3
> 
> Same situation.
> 
> | Test 3:
> | >>> c3 = [[0,0],[0,0],[0,0]]
> 
> Here's what you wanted -- a 3-element list where each element is a
> _separate_ list.
> 
> 
> A shorter way of writing that (for longer lists) is :
>     c = []
>     for i in range(3) :
>         c.append( [0]*2 )
> 
>     or
> 
>     c = [ [0]*2  for i in range(3) ]
> 
> 
> -D
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582