I am using the below code to prepare a matrix of m×n, which should contain integers in a given range with randomness. I am unable to trace the operation of list.clear() which makes so that all rows of my matrix to be identical. If I assign a new list instead of list.clear() it works fine. I will post the code and output below. What is the reason for the behavior I am witnessing using clear()?
code
import random
m = 5 # number of rows
n = 6 # number of columns
mat = [] # a list for making the rows of matrix
matrix = []
for i in range(m):
mat.clear() # works fine if I use mat=[]
print(mat)
for i in range(n):
mat.append(random.randint(0, 2))
print(mat)
matrix.append(mat)
print(matrix)
output using clear(): all rows of the matrix are identical
[]
[1, 1, 2, 0, 1, 0]
[[1, 1, 2, 0, 1, 0]]
[]
[2, 0, 2, 0, 2, 1]
[[2, 0, 2, 0, 2, 1], [2, 0, 2, 0, 2, 1]]
[]
[1, 2, 2, 0, 0, 1]
[[1, 2, 2, 0, 0, 1], [1, 2, 2, 0, 0, 1], [1, 2, 2, 0, 0, 1]]
[]
[2, 0, 0, 1, 0, 0]
[[2, 0, 0, 1, 0, 0], [2, 0, 0, 1, 0, 0], [2, 0, 0, 1, 0, 0], [2, 0, 0, 1, 0, 0]]
[]
[2, 1, 1, 0, 2, 0]
[[2, 1, 1, 0, 2, 0], [2, 1, 1, 0, 2, 0], [2, 1, 1, 0, 2, 0], [2, 1, 1, 0, 2, 0], [2, 1, 1, 0, 2, 0]]
Process finished with exit code 0
output using mat=[]
[]
[0, 2, 0, 2, 1, 2]
[[0, 2, 0, 2, 1, 2]]
[]
[2, 1, 1, 2, 0, 0]
[[0, 2, 0, 2, 1, 2], [2, 1, 1, 2, 0, 0]]
[]
[0, 0, 0, 0, 2, 2]
[[0, 2, 0, 2, 1, 2], [2, 1, 1, 2, 0, 0], [0, 0, 0, 0, 2, 2]]
[]
[0, 2, 1, 1, 1, 0]
[[0, 2, 0, 2, 1, 2], [2, 1, 1, 2, 0, 0], [0, 0, 0, 0, 2, 2], [0, 2, 1, 1, 1, 0]]
[]
[2, 2, 0, 1, 1, 1]
[[0, 2, 0, 2, 1, 2], [2, 1, 1, 2, 0, 0], [0, 0, 0, 0, 2, 2], [0, 2, 1, 1, 1, 0], [2, 2, 0, 1, 1, 1]]
Process finished with exit code 0