[Matrix-SIG] Problem with arrays of arrays
Marc Keller
mkeller@cybercable.fr
Sun, 19 Dec 1999 23:35:37 +0100
Vincenzo Tschinke wrote:
> Hi!
>
> I am doing some basic molecular connectivity operation (graphs). Trying to
> convert a list of bonds (list of edges) into a connectivity table (for each
> vertex [atom], list of connected vertices), by filling an array of arrays, I
> got the right or wrong result depending on how I define the initial arrays.
>
> If I define an array of N emtpy arrays as
>
> array_of_empties = N * [[]]
>
> I get the *wrong* result. If I use the more exotic definition
>
> array_of_empties = map ( lambda x : [] , range( N ))
>
> I get the *right* result. Note that after being created, such two arrays
> compare as equal.
>
> Please see the listing below.
>
> Is there anything wrong with the first definition, or do we have a
> Python bug here?
>
> ===========================================================================
>
> Python 1.5.2b1 (#47, Jan 13 1999, 15:14:59) [CW PPC w/GUSI w/MSL]
>
> >>> ee=[[1,2],[1,3],[1,4]] # 3 edges : 3 vert. connected to centr. vertex
> >>> ee
> [[1, 2], [1, 3], [1, 4]]
> >>> aa=4*[[]] # array of four empty arrays
> >>> AA=map(lambda x : [], range(4)) # same as above
> >>> aa==AA # arrays are equal !!!
> 1
> >>> for p in ee: # build table of connected verteces
> ... i=p[0]
> ... j=p[1]
> ... aa[i-1].append(j)
> ... aa[j-1].append(i)
> ... AA[i-1].append(j)
> ... AA[j-1].append(i)
> ...
> >>> aa # wrong result !!!
> [[2, 1, 3, 1, 4, 1], [2, 1, 3, 1, 4, 1], [2, 1, 3, 1, 4, 1], [2, 1, 3, 1, 4, 1]]
> >>> AA # correct result
> [[2, 3, 4], [1], [1], [1]]
> >>> aa==AA
> 0
> >>>
>
> =======================
> Vincenzo Tschinke
> Kernmattstr. 24
> CH-4102 Binningen
> Switzerland
> +4161 422 1991 (T+F)
> tschinke@swissonline.ch
> =======================
>
> _______________________________________________
> Matrix-SIG maillist - Matrix-SIG@python.org
> http://www.python.org/mailman/listinfo/matrix-sig
Using N * [[]], you are building a list with 4 references to the same list.
Using map ( lambda x : [] , range( N )), each call to lambda produces a new empty list.
Your exemple in an other way:
>>> aa=[[],[],[],[]]
>>> for p in ee: # build table of connected verteces
... i=p[0]
... j=p[1]
... aa[i-1].append(j)
... aa[j-1].append(i)
...
>>> aa
[[2, 3, 4], [1], [1], [1]]
>>>