Help! I need a list, not a pointer to it

Gabriel Genellina gagsl-py at yahoo.com.ar
Tue Nov 21 18:49:18 EST 2006


At Tuesday 21/11/2006 19:53, Sorin Schwimmer wrote:

>solutions=[]
>matrix=[[1.0], [0], [0]]
>j=0
>while j<c:
>   [...modify matrix...]
>   print matrix
>   solutions.append(matrix) # same result with matrix[:]
>print solutions
>
>gives:
>[[0], [1.0], [0]]
>[[0], [0], [1.0]]
>[[1.0], [0], [0]]
>[[[1.0], [0], [0]], [[1.0], [0], [0]], [[1.0], [0], [0]]]
>(i.e. the last value of matrix, three times)
>
>How can I end up with:
>[[0], [1.0], [0]]
>[[0], [0], [1.0]]
>[[1.0], [0], [0]]
>[[[0], [1.0], [0]], [[0], [0], [1.0]], [[1.0], [0], [0]]]
>(i.e. each value of matrix)?

Using matrix[:] gives you a _shallow_ copy of matrix - a new list, 
but its elements (lists themselves) are the original ones.
You may want to use deepcopy() instead (or redesign your algorithm to 
not use those inner lists).


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list