How to Create a MATRIX or 2D LIST in Python by taking inputs from the user for required number of rows and columns along with the values to be inserted in the each index.

Python Code to create a 2D List or Matrix:

matrix=[]
r=int(input("Enter count of rows:"))
c=int(input("Enter count of columns:"))
for i in range(r):

row=[]
for j in range(c):
value=int(input("enter value:"+str(i)+","+str(j)+":"))
row.append(value)
   matrix.append(row)
print(matrix)

Python Code to Calculate Sum of Columns in a Matrix or 2D List

1	M = [[8, 2, 4], [6, 4, 2], [9, 4, 5]]
2	R = 3
3	C = 3
4	sum=[]
5	total=0
6	for i in range(R):
7	    for j in range(C):
8	        total+=M[j][i]
9	    sum.append(total)
10	    total=0
Python Code to Calculate Sum of Columns in a Matrix or 2D List


How to convert a STRING into LIST code in Python

text="How to convert a STRING into LIST code in Python"
clist=text.split()
print(clist)
print(type(clist))


How to convert a LIST into STRING code in Python

dlist = " ".join(clist)
print(dlist)
print(type(dlist))

Use of pop() function in LIST
pop() function is used to remove and capture the value. You can pass index of an element as an argument as per the requirement. Incase no argument is passed into the function then it would remove the last element from input.

Score = [[45, 72, 63, 24],
       [83, 52, 116, 27],
       [34, 19, 10, 111],
       [78, 87, 63, 65]]

for i in range(len(Score):
  print(Score[i].pop(), end=" ")

output: 24,27,111,65 
e.g. if you want to analyse the performance of a player on last match of every series.

By Pankaj

Leave a Reply

Your email address will not be published. Required fields are marked *