0
matrix = [[[]]*3]*3

for i in range(3):
    for j in range(3):
        matrix[i][j] = random.randint(10,100)

How is it filled in:

0  i

0  j

[[98, [], []], [98, [], []], [98, [], []]]  matrix

[98, [], []] i=0

1  j

[[98, 80, []], [98, 80, []], [98, 80, []]]  matrix

[98, 80, []] i=0

2  j

[[98, 80, 52], [98, 80, 52], [98, 80, 52]]  matrix

[98, 80, 52] i=0

1  i

0  j

[[61, 80, 52], [61, 80, 52], [61, 80, 52]]  matrix

[61, 80, 52] i=1

1  j

[[61, 70, 52], [61, 70, 52], [61, 70, 52]]  matrix

[61, 70, 52] i=1

2  j

[[61, 70, 24], [61, 70, 24], [61, 70, 24]]  matrix

[61, 70, 24] i=1

2  i

0  j

[[22, 70, 24], [22, 70, 24], [22, 70, 24]]  matrix

[22, 70, 24] i=2

1  j

[[22, 50, 24], [22, 50, 24], [22, 50, 24]]  matrix

[22, 50, 24] i=2

2  j

[[22, 50, 72], [22, 50, 72], [22, 50, 72]]  matrix

[22, 50, 72] i=2

I've been getting to know Python for a week now and would like an explanation. I expected that each nested list would be filled in separately, but I may not understand some nuances or do not see a problem.

As I see it: The iteration between cycles goes as intended, and the appeal through the indexing operator should go as it should, that is, list[0][0] 1 element of the base list, which is a nested list in which I already refer to its 1 element. But the appeal occurs to all 1 elements of nested lists at once.

I made an option where I bypassed this problem by reading about the 3-dimensional array text

def matrix_generator(i,j):
    '''
    Generates a matrix
    Matrix generator(i,j) with random values 
    '''
    #Local variables
    matrix = [[[]]*j]*i
    matrix_dublicate = [[]]*i
    
    for row in range(i):     
        for column in range(j):
            matrix[row][column] = random.randint(10,100)
            
        #Creating a duplicate   
        else:
            matrix_dublicate[row] = matrix[row].copy()
            
    #Duplicate implementation        
    for i in range(len(matrix)):
        matrix[i] = matrix_dublicate[i]
        
    return matrix

But I believe I have not solved this problem. In this regard, is there a cleaner way to solve this problem? And I would like to read about how and why this problem occurs at all?

wovano
  • 4,543
  • 5
  • 22
  • 49
Lukoris
  • 1
  • 2

0 Answers0