Multi-Dimensional Lists
Basics
Multi-dimensional lists are the lists within lists.
There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over.
We have already seen 1-D List.
MyList = [1,2,3,4,5]
2-D List
MyList = [["Shashank","Muskan"],["Shivam","Akshat"]]
3-D List
MyList = [[[1,2],[3,4]]]
Creating a 1-D List
Create a file 1_D.py
2_D.py
# Python program to create a 1-D list
# with all 0s
n=5
My_List_1D = [0 for i in range(n)]
print(My_List_1D)
Output
[0, 0, 0, 0, 0]
Creating a 2-D List
Create a file 2_D.py
2_D.py
# Python program to create a m x n matrix
# with all 0s
m = 4
n = 5
My_List_2D = [[0 for i in range(n)] for i in range(m)]
print(My_List_2D)
Output
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Creating a 3-D List
Create a file 3_D.py
3_D.py
# Python program to create a m x n x o matrix
# with all 0s
m = 2
n = 2
o = 2
My_List_3D = [[[for i in range(o)] for i in range(n)] for i in range(m)]
print(My_List_3D)
Output
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]