Open In App

Multi-dimensional lists in Python

Last Updated : 09 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report
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. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python.
Accessing a multidimensional list:
Approach 1:
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
Approach 2: Accessing with the help of loop.
Output:
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
Approach 3: Accessing using square brackets. Example:
Output:
2 4 6 8 
1 3 5 7 
8 6 4 2 
7 5 3 1
Creating a multidimensional list with all zeros:
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Methods on Multidimensional lists
1. append(): Adds an element at the end of the list. Example:
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]
2. extend(): Add the elements of a list (or any iterable), to the end of the current list.
Output:
[[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
3. reverse(): Reverses the order of the list.
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [20, 16, 12, 8, 4]]

Next Article
Article Tags :
Practice Tags :

Similar Reads