Nested List or Matrix using List
A list in inside another list is called nested
or a matrix. For example
>>>Student =[101,
‘Narain Ji’ ,[76,98,56,76,89]] # nested list
>>>
Marks=[[87,'Jyotsna'],[98,'Ankita'],[77,'Vanshika']]
Index
from left |
0 |
1 |
2 |
[0][0]
[0][1] |
[1][0]
[1][1] |
[2][1]
[2][2] |
|
List
of elements |
[87,'Jyotsna'] |
[98,'Ankita'] |
[77,'Vanshika'] |
Index
from right end |
[-3][-2] [-3][-1] |
[-2][-2] [-2][-1] |
[-1][-2] [-1][-1] |
[-3][0]
[-3][1] |
[-2][0] [-2][1] |
[-1][0] [-1][1] |
|
-3 |
-2 |
-1 |
Creating Matrix
A matrix is a
rectangular table of elements or two dimensional array. The following is a 3x3
matrix, meaning there are 3 rows and 3 columns.
If we know the number
of rows(n) and columns(m) of a matrix, then the syntax is :
Matrix=[[0 for col in range(m)],for row
in range(m)]
Processing of Matrix :
Source Code
row_num =
int(input("Input number of rows: "))
col_num =
int(input("Input number of columns: "))
multi_list = [[0 for
col in range(col_num)] for row in range(row_num)] # Create matrix
Display
matrix |
multi_list[row][col]= row*col
print(multi_list[row][col],end="\t")
print()
Input Matrix/nested list elements from keyboard and show matrix
Source Code:
rows = int(input("Input number of
rows: "))
cols = int(input("Input number of
columns: "))
Matrix = [[0 for col in range(cols)] for
row in range(rows)] # declare matrix
for row in range(rows):
print("Enter values for row -> ",row)
for col in range(cols):
print("Matrix[",row,"][",col,"]->
",end="")
Matrix[row][col]=int(input()) # input elements from keyboard
print("\n Display Matrix ")
for row in range(rows):
for col in range(cols):
print(Matrix[row][col],end="\t")
print()
No comments:
Post a Comment