Python Programming

Two Dimensional List in Python

In Programming, Python by Baqir Ali

Two-dimensional list stores data in the form of rows and columns or you can say in the form of a matrix. Example

[10,20,30]
[40,50,60]

In the above example, there are two rows and each row has three columns which is an example of two dimensional (2d) list.

How to define a two-dimensional list in Python

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

In the above code, there are four rows and each row has three columns.

matrix=[
    [2,3,6],
    [4,5,2],
    [5,4,7],
    [1,2,5]
]
print(matrix[1][1]) 
#prints the value @ 1 row and 1 column
#remember it starts from 0

Output: 5

In order to print a 2D list we use two square brackets

Loop through a two dimensional list in Python

matrix=[
    [2,3,6],
    [4,5,2],
    [5,4,7],
    [1,2,5]
]
for row in range(4):
    for col in range(3):
        print(matrix[row][col],end=' ')
    print()

Output:

2 3 6
4 5 2
5 4 7
1 2 5

Support us by sharing this post