Fill a 2D list with random numbers in python

Viewed 323

I have created a function to fill a 2D array, but it does not work as intended:

from random import *

def fill_matrix(maxrow, maxcol):
    mymatrix = [ [ None ] * maxrow ] * maxcol
    for row_index in range(0, len(mymatrix)):
        for col_index in range(0, len(mymatrix[row_index])):
            mymatrix[row_index][col_index] = randint(0, 9)
            print(row_index, col_index, ": ", mymatrix)
    print(mymatrix)
                               
fill_matrix(3, 4)

But it always fills every column with the same number, although I specified [row_index][col_index]:

Result output:

0 0 :  [[0, None, None], [0, None, None], [0, None, None], [0, None, None]]
0 1 :  [[0, 2, None], [0, 2, None], [0, 2, None], [0, 2, None]]
0 2 :  [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
1 0 :  [[4, 2, 0], [4, 2, 0], [4, 2, 0], [4, 2, 0]]
1 1 :  [[4, 1, 0], [4, 1, 0], [4, 1, 0], [4, 1, 0]]
1 2 :  [[4, 1, 6], [4, 1, 6], [4, 1, 6], [4, 1, 6]]
2 0 :  [[0, 1, 6], [0, 1, 6], [0, 1, 6], [0, 1, 6]]
2 1 :  [[0, 2, 6], [0, 2, 6], [0, 2, 6], [0, 2, 6]]
2 2 :  [[0, 2, 3], [0, 2, 3], [0, 2, 3], [0, 2, 3]]
3 0 :  [[8, 2, 3], [8, 2, 3], [8, 2, 3], [8, 2, 3]]
3 1 :  [[8, 7, 3], [8, 7, 3], [8, 7, 3], [8, 7, 3]]
3 2 :  [[8, 7, 3], [8, 7, 3], [8, 7, 3], [8, 7, 3]]
[[8, 7, 3], [8, 7, 3], [8, 7, 3], [8, 7, 3]]
3 Answers

when you do arr= [[None]*2]*3 you create a list with 3 lists referencing to same list. so if one list changes all the other ones will change. So replace mymatrix = [ [ None ] * maxrow ] * maxcol by

mymatrix = [ [ None for i in range (maxrow) ] for j in range (maxcol)]

you can try it

import numpy as np
list2D = (np.random.random((N,N))).tolist()

output, when N=5:

[[0.5443335192306711, 0.06610164916627725, 0.9464264551530688, 
0.8714989296172226, 0.343053651834623], [0.4694855513495554, 
0.9109844708363358, 0.9857587537047011, 0.7607561949627727, 
0.46307440609410333], [0.050891396239376996, 0.13672955575820833, 
0.8549886951728779, 0.8803310239366302, 0.04983877880553622], 
[0.3503177755755804, 0.08222507697906556, 0.7144017087408304, 
0.6117493050623465, 0.68059136839199], [0.2244599257314427, 
0.06203059400599176, 0.9342379337438128, 0.5204524652150645, 0.44055560620795253]]

see this link: enter link description here

Try using numpy:

import numpy as np

print(np.random.randint(0,9,size=(4,3)))
Related