0

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.

2 Answers2

2

This is attributed to how Python treats variables, when you do matriz = [[0] * 5] * 5, each element of the list matriz is a pointer to the same list in memory.

To accomplish what you want to do, use this matriz = [ [0]*5 for n in xrange(5)] so that each sub-list is its own list in memory.

Brian
  • 1,659
  • 12
  • 17
1

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]]
user2390182
  • 72,016
  • 6
  • 67
  • 89