Creating a matrix?

Peter Hansen peter at engcorp.com
Fri Apr 2 10:42:40 EST 2004


Peter Maas wrote:

> Ivan Voras wrote:
> 
>> Is there a nice(r) way of creating a list of uniform values? I'm 
>> currently using: list('0'*N), which makes a string and then chops it 
>> up into a list. I need it to create a NxN matrix:
>>
>  > matrix = [list('0'*N) for i in range(N)]
> 
> matrix = [['0']*N]*N

Sorry, Peter, but that's a rookie mistake:

 >>> matrix = [['0'] * 4] * 4
 >>> matrix
[['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', 
'0', '0
', '0']]
 >>> matrix[1][2] = '1'
 >>> matrix
[['0', '0', '1', '0'], ['0', '0', '1', '0'], ['0', '0', '1', '0'], ['0', 
'0', '1
', '0']]

Notice that each of the inner lists contains four seperate references
to the string '0', but the outer repetition simply copies the inner
list four times, resulting in four references to the same inner list!
Changing any one element affects the same entry in each of the other
three lists...

-Peter



More information about the Python-list mailing list