Troubles taking a matrix from user's input, defining it as a list of lists

Viewed 42

I want to make a program that takes inputs from the user to build an n x n matrix.

This is what I tried to do:

dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row)
    row.clear()
print("Your matrix is:")
print(matrix)

And although the printed rows are fine, the final matrix I print consists only of empty lists. It looks something like the following:

[[],[],[]]

Why is this happening?

2 Answers

.clear() modifies the row list in-place, and you're using the same list across different iterations of the outer loop. Under the hood, matrix list consists of references that point to the same memory as row. So, the removal of all the elements in row is reflected in the matrix as well.

To resolve, reassign the row variable to an empty list at the start of each iteration of the outer loop. This separates the memory used to store each row.

dim=int(input("Dimension of your matrix? "))
matrix=[]
for i in range(dim):
    row = []
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row)
print("Your matrix is:")
print(matrix)

You are using a shallow copy when you append a row in your matrix. So it just keep the address of your row, and when you clean the row at the end of your loop the amounts in your matrix is also cleaned. You need to use a deep copy. So, use this code, the when you are appending a new row:

 matrix.append(row.copy())

The complete program will be:

dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row.copy())
    row.clear()
print("Your matrix is:")
print(matrix)
Related