References and copies
Yermat
loic at yermat.net1.nerim.net
Mon Jun 21 21:48:30 CEST 2004
Thomas Philips a écrit :
> I want to represent an NxN matrix by a list containing N lists, each
> of which has N elements. Initially the elements are set to " ". For
> N=2, I write
>
>
>>>>x = [" "][:]*2 #assignment creates references, not copies!
>>>>x
>
> [' ', ' ']
>
>>>>y = [x[:]]*2
>>>>[...]
>
> I fail to see the error in my first attempt. Where is the fly in the
> ointment?
>
> Thomas Philips
Your trboules come from this line: y = [x[:]]*2 because you do not copy
the x twice but just assign a copy of x twice...
see the following:
>>> x = [" "]*2
>>> x
[' ', ' ']
>>> x = [" "]*2
>>> y = [x]*2
>>> y
[[' ', ' '], [' ', ' ']]
>>> id(y[0])
8303600
>>> id(y[1])
8303600
>>>
>>> y = [[" "] *2, [" "]*2]
>>> id(y[0])
8306544
>>> id(y[1])
8305424
>>>
--
Yermat
More information about the Python-list
mailing list