Thursday, 29 June 2023

Two dimensional lists in Python

We can model a matrix using two dimensional lists in Python.

 

Example

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

 

Above snippet defines a matrix using two dimensional lists. Every element in the two-dimensional list is a list.

 

'matrix[0]' return first row of the matrix.

'matrix[1]' return second row of the matrix.

'matrix[2]' return third row of the matrix.

 

Access individual elements

matrix[row_index][column_index] select the element at given row and column.

 

For example, matrix[1][2] return the element at row 2 and column 3 which is 6.

 

matrix.py
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix)

print('1st row : ', matrix[0])
print('2nd row : ', matrix[1])
print('3rd row : ', matrix[2])

print('Element at row 2 and column 3 : ', matrix[1][2])

 

Output

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
1st row :  [1, 2, 3]
2nd row :  [4, 5, 6]
3rd row :  [7, 8, 9]
Element at row 2 and column 3 :  6

 


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment