Spring sales Spring sales
Get up to 60 % extra points for free! More info

Lesson 10 - Multidimensional lists in Python

In the previous lesson, Strings in Python - Split, we learned how to use the split() string method. Today's tutorial is basically a bonus when it comes to Python basic constructs. We'll discuss what we call multidimensional lists (arrays). Essentially, you could skip directly to the next lesson, however, I highly recommend that you finish this one, so you could understand the remaining techniques. After all, this is still just the basics.

We've already worked with one-dimensional lists, which we can imagine as a row of boxes in our computer's memory.

List structure in Python

(A list of eight numbers can be seen in the image)

Although it's not too common, you may sometimes encounter multidimensional lists. Especially, when it comes to game applications.

Two-dimensional list

A good representation of a 2-dimensional list is a grid because technically, it is one. A practical application for 2-dimensional lists would be to use them to store the available seats in a cinema. Here's a visual representation of what I'm referring to:

The 2d list structure in Python

(We can see the available seats of the cinema in the picture )

Of course, a cinema would be bigger in real life, but this list is just fine as an example. 0 means the seat is available, 1 stands for one that isn't. Later, we could also add 2 for reserved seats and so on. It'd be more appropriate to create our own data type (called enumerable) for these states, but we'll get into that later. For now, we'll work with numbers.

In Python, we declare the 2D array (list) like a list of lists:

cinema = []

for j in range(5):
    column = []
    for i in range(5):

As first, we create an empty one-dimensional list. Then we generate 5 more lists (columns) using a for loop, fill each list with 5 zeros using a nested loop and add the list to the original list as a new item.

The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first.

We've just created a table full of zeros.

Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use for loops to create a row of 1s :) To access an item of the 2D list we have to enter two coordinates.

cinema[2, 2] = 1 # center
for i in range(1, 4): # fourth row
    cinema[i][3] = 1
for i in range(5): # the last row
    cinema[i][4] = 1

The output

We'll print the list using a loop as we did before. We'll need 2 loops for the 2d list, the first one will iterate over columns and the second one over rows. As proper programmers, we won't specify the number of rows and columns directly into the loop because it may change in the future. We know the len() function so we can easily ask how many columns is in the outer list and how many items is in the inner one. We have to keep in mind the outer list can be empty.

We'll nest the loops in order so that the outer loop iterates over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Both loops must have a different control variable:

cols = len(cinema)
rows = 0
if cols:
    rows = len(cinema[0])
for j in range(rows):
    for i in range(cols):
        print(cinema[i][j], end = "")

The result:

Console application

N-dimensional arrays

Sometimes, it may be useful to create a list of even more dimensions. We can all at least imagine a 3D list. Adding on to the cinema analogy, we'll say ours has multiple floors or generally more rooms. The visualization would then look like this:

The 3D list structure in Python

We can create the 3D array the same way we created the 2D array:

cinemas = []

for k in range(5):
    cinema = []
    for j in range(5):
        column = []
        for i in range(5):

The code above creates the 3D array you saw in the picture. We can access it through the indexers, square brackets, like before, but now we have to enter 3 coordinates.

cinemas[3][2][1] = 1 # the second-floor cinema, the third row, the fourth seat

Shortened initialization of multidimensional lists

I'll also mention that even multidimensional lists can be initialized with values directly (the code creates and initializes a crowded cinema room as you can see in the picture):

cinema =[
    [ 0, 0, 0, 0, 1 ],
    [ 0, 0, 0, 1, 1 ],
    [ 0, 0, 1, 1, 1 ],
    [ 0, 0, 0, 1, 1 ],
    [ 0, 0, 0, 0, 1 ]

(The list in this code is rotated since we define columns which are declared as rows here).

Jagged arrays

In some cases, we don't even have to "waste" memory for the entire table. Instead, we're able to create jagged multidimensional lists.

Jagged lists in Python

We can create it either using loops or use a shortened initialization (the code below creates the jagged list from the picture):

jagged_list = [
    [15, 2, 8, 5, 3],
    [3, 3, 7],
    [9, 1, 16, 13],

Then, we'd print it like this:

for column in jagged_list:
    for item in column:
        print(item, end = " ")

In conclusion, I would like to add that some people who can't use objects properly, use 2D lists or dictionaries to store multiple sets of data of a single entity. e.g. imagine that we want to store the length, width, and height of five cell phones. Although you may think that a 3D list would be best for the situation, it can be pulled off with an ordinary 1D list (specifically a list of objects of the Phone type). We'll go over all of that in the object-oriented programming course. If you feel like you could still use some more practice, go ahead and give the exercises for this lesson a shot.

In the next lesson, Tuples, sets, and dictionaries in Python, we'll look at basic math functions.



Downloaded 0x (904 B)
Application includes source codes in language Python



Article has been written for you by David Capka
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Previous article
Strings in Python - Split
All articles in this section
Python basic constructs
Next article
Tuples, sets, and dictionaries in Python
Activities (10)




To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!