Lesson 10 - Multidimensional lists in Python
Lesson highlights
Are you looking for a quick reference on multidimensional lists in Python instead of a thorough-full lesson? Here it is:
Shortened initialization of a 2D array:
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 ] ]
Writing 1
at the position
[1][0]
:
cinema[1][0] = 1
Reading the value (now 1
) at the position
[1][0]
:
{PYTHON}
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 ]
]
cinema[1][0] = 1
print(cinema[1][0])
Printing the whole 2D array:
{PYTHON}
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 ]
]
cinema[1][0] = 1
for column in cinema:
for item in column:
print(item, end = " ")
print()
Generating an empty 2D array of a given size:
{PYTHON}
cinema = []
for j in range(5):
column = []
for i in range(5):
column.append(0)
cinema.append(column)
for column in cinema:
for item in column:
print(item, end = " ")
print()
Would you like to learn more? A complete lesson on this topic follows.
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.

(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:

(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): column.append(0) cinema.append(column)
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 1
s 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 1
s 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:
{PYTHON}
# declaration and adding columns
cinema = []
for j in range(5):
column = []
for i in range(5):
column.append(0)
cinema.append(column)
# filling with data
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
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 = "")
print()
The result:
Console application
00000
00000
00100
01110
11111
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:

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): column.append(0) cinema.append(column) cinemas.append(cinema)
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.

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], [], [5] ]
Then, we'd print it like this:
{PYTHON}
jagged_list = [
[15, 2, 8, 5, 3],
[3, 3, 7],
[9, 1, 16, 13],
[],
[5]
]
for column in jagged_list:
for item in column:
print(item, end = " ")
print()
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.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 14x (904 B)
Application includes source codes in language Python