I'm trying to understand what some Python keywords and functions do by reviewing this code that takes in matrices and adds the numbers within the said matrices, but I'm having some troubles understanding what some of these lines of code mean. An explanation that's easy to understand for programming newbies like me would be great help.
Here is the code.
# input operation
op = input("Enter operation : ")
#if operation is addition
if(op == "add"):
# A and B for two matrix
A = []
B = []
#input dimensions for A matrix,
A_row, A_col = input("Dimension for matrix A : ").split()
#convert dimensions to int type
A_row = int(A_row)
A_col = int(A_col)
#input, elements of matrix A
for i in range(A_row):
# input rows wise
print("Enter elements for row", i+1)
row = list(map(int, input().split()))[:A_col]
#append row to matrix A
A.append(row)
#input, dimension for matrix B
B_row, B_col = input("Dimension for matrix B : ").split()
#convert to increate a matt type
B_row = int(B_row)
B_col = int(B_col)
#input for matrix B, elements
for i in range(A_row):
print("Enter elements for row", i+1)
row = list(map(int, input().split()))[:B_col]
B.append(row)
#create a matrix for result with 0 of size of matrix A size
result = [([0]*A_col) for i in range(A_row)]
# loop and do addition of A and b , store to result matrix
for i in range(A_row):
for j in range(A_col):
result[i][j] = A[i][j] + B[i][j]
#print result
print("result")
for row in result:
for x in row:
print(x, end=' ')
print()
#if operation is not valid
else:
print("Invalid operation")
My Questions:
- What is the purpose of that
[:A_col]
at the end ofrow = list(map(int, input().split()))[:A_col]
? - Now this is where I get really confused. Everything from
result
afterwards seems to be a blur to me. Especially thatresult = [([0]*A_col) for i in range(A_row)]
. What does that specific line mean and what exactly is its purpose in this code? The comment placed right above it does not really help me.
I know what bracket operators do but I fail to understand the purpose of that [:A_col]
at the end of row = list(map(int, input().split()))[:A_col]
.