Multi-dimensional lists in Python

PythonServer Side ProgrammingProgramming

Lists are a very widely use data structure in python. They contain a list of elements separated by comma. But sometimes lists can also contain lists within them. These are called nested lists or multidimensional lists. In this article we will see how to create and access elements in a multidimensional list.

Creating Multi-dimensional list

In the below program we create a multidimensional list of 4 columns and 3 rows using nested for loops.

Example

 Live Demo

multlist = [[0 for columns in range(4)] for rows in range(3)]
print(multlist)

Output

Running the above code gives us the following result −

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Extending Multi-dimensional lists

We can add elements to the list created above using methods that are available to the lists. We will use the methods append and extend to achieve this. Both methods are shown in the program below.

Example

 Live Demo

multlist = [["Mon","Tue","Wed"], [2, 4, 9,], [1,1.5, 2]]
multlist.append(["Phy","Chem","Math"])
print(multlist)

multlist[0].extend(["Thu","Fri"])
print(multlist)

Output

Running the above code gives us the following result −

[['Mon', 'Tue', 'Wed'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]
[['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]

Accessing Multi-dimensional list

We can access the elements in multidimensional list using for loops as shown in the below program. We design nested for loops to first access the rows and then access the columns.

Example

multlist = [[1,5,9], [2, 4, 9,], [1,1, 2]]
for i in range(len(multlist)) :
   for j in range(len(multlist[i])) :
      print(multlist[i][j], end=" ")
   print()

Output

Running the above code gives us the following result −

1 5 9
2 4 9
1 1 2
raja
Published on 10-Jul-2020 14:48:05
Advertisements