Michael Five Michael Five - 5 months ago 7
Python Question

Assign random numbers in double list of zeros

I have the following code in python:

#-*-coding:cp1252-*-
from random import randint

matriz = [[0] * 5] * 5
print matriz
for i in range(5):
for j in range(5):
numero = randint(0,10)
matriz[i][j] = numero

for i in matriz:
print i


Why the all rows are the same???

by example, a random double list generated:

[0, 5, 1, 0, 10]
[0, 5, 1, 0, 10]
[0, 5, 1, 0, 10]
[0, 5, 1, 0, 10]
[0, 5, 1, 0, 10]


Thanks.

Answer

Your matrix consists of 5 references to the same list. The shortest way to avoid it would be some nested comprehension along the lines of:

> m = [[random.randint(1,10) for _ in xrange(5)] for _ in xrange(5)]
> m
[[9, 4, 4, 10, 10], [1, 2, 4, 3, 5], [3, 4, 8, 9, 10], [5, 9, 4, 3, 3], [3, 3, 8, 6, 7]]
Comments