pythonarraysrandommatrixrows

Python: Why randint on a matrix keeps giving me the same rows


I'm using Python 3 and with this code:

import random
mat = [[0]*5]*5

for i in range (0,5) :
    for j in range (0,5)  :
        mat[i][j] = random.randint(10,50)

print (mat)

I'm getting results like this:

[[26, 10, 28, 21, 15], [26, 10, 28, 21, 15], [26, 10, 28, 21, 15], [26, 10, 28, 21, 15], [26, 10, 28, 21, 15]]

The rows are equal each other, but the loop seems to be alright.

What is the problem?


Solution

  • The problem is this line:

    mat = [[0]*5]*5
    

    What that does is to create a single list of 5 zeros ([0]*5) and then create 5 more references to that same list.

    The solution which gets you around this problem:

    mat = [[0]*5 for _ in xrange(5)]
    

    this creates a list of 5 zeros 5 separate times meaning that all the lists are independent.