Recently I was trying to implement a matrix using lists in Python. I understand that numpy would be more suitable for the job, but I wanted to try it with lists. Here is the code:
def input_array(): #Take the list elements as input from user
array = []
row = input("Enter the num of rows: ")
col = input("Enter the num of cols: ")
for i in range(int(row)):
arr = []
for j in range(int(col)):
a = eval(input("Enter an element: "))
arr.append(a)
array.append(arr)
print(array)
return array
def print_array(array): #Print the list as a matrix
for i in range(len(array)):
for j in range(len(array[i])):
print(array[i][j], end = " ")
print()
def getRowSum(array): #To get the sum of rows and print them beside respective rows
arr = array[:]
for i in range(len(arr)):
summ = 0
for j in arr[i]:
summ += j
arr[i].append(summ)
print_array(arr)
array = input_array()
print_array(array)
getRowSum(array)
print(array)
When I run the program, I am facing an odd issue. As per my knowledge, when I am copying a list using [:]
, then any change to the duplicate list will not affect the original list. But this is not happening in this case. You will see that when I use print(array)
after executing getRowSum()
, the list changes even though I worked on a copy of the list in the function.
You would understand it better if you execute the code yourself.
Please tell as to what I am doing wrong and how should I really proceed with it.