0

In below Python program python program for matrix addition of 2*2 giving same output (Wrong) for both rows when matrix assigned zero matrix3=[[0]*col]*row and assigned values to matrix. Give correct output for append operation.

row = int(input("Enter the number of rows:"))
col = int(input("Enter the number of columns:"))
matrix1 = []

for i in range(row):
    a1 =[]
    for j in range(col):      
         a1.append(int(input()))
    matrix1.append(a1)

print("1st matrix")
for i in range(row):
    for j in range(col):
        print(matrix1[i][j], end = " ")
    print()

print("Enter Elements of 2nd Matrix")
matrix2=[]
for i in range(row):
    a2 =[]
    for j in range(col):      
         a2.append(int(input()))
    matrix2.append(a2)

print("2nd matrix")
for i in range(row):
    for j in range(col):
        print(matrix2[i][j], end = " ")
    print()

matrix3=[[0]*col]*row

print("additing matrices:")

'''
#Give Correct output
for i in range(row):
   matrix3.append([])
   for j in range(col):
       matrix3[i].append(matrix1[i][j]+matrix2[i][j])
'''

#Give Wrong Output for 2*2 matrix with both rows as same 
for i in range(row):
   for j in range(col):
       matrix3[i][j]=matrix1[i][j]+matrix2[i][j]

for i in range(row):
    for j in range(col):
        print(matrix3[i][j], end = " ")
    print()

Output For Code

enter image description here

nucsit026
  • 652
  • 7
  • 16
krishna
  • 25
  • 4
  • see https://stackoverflow.com/questions/59925864/initializing-a-2-d-python-list-as-933-seems-to-create-references-to-the-sa/59925932#59925932 – Andrew Merrill Jan 27 '20 at 06:23

1 Answers1

0

try this in your matrix calculation section

matrix3 = []
for i in range(row):
   temp = []
   for j in range(col):
       temp.append(matrix1[i][j] + matrix2[i][j])
   matrix3.append(temp) 

Update: try declare the matrix3 variable as

matrix3 = [[0]*col for _ in range(row)]

It works fine.

matrix3 = [[0]*col]*row

Here, matrix3[0] and matrix3[1] this two nested list with same reference, you can check the reference id(matrix3[0]), that means if you change matrix3[0] it'll change matrix3[1]

Fahim Ahmed
  • 141
  • 11
  • I know this (code written in comment section). But want to know why "matrix3[i][j]=matrix1[i][j]+matrix2[i][j]" is not working. As I am teacher, I want explanation. – krishna Jan 27 '20 at 06:55
  • as the comment above, it's create a reference of a same list. https://stackoverflow.com/a/2739564/5277295 – Fahim Ahmed Jan 27 '20 at 08:25