Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding creating a 2D list with nested loops

How do nested for loops (in this case double for loops) work in creating a 2D list.

For example I would like to have a 2x2 matrix that is initialized with 0 as every element.

I got this:

x = [[0 for i in range(row)] for j in range(col)]

where row is defined to be the number of rows in the matrix and col is defined to be the number of columns in the matrix. In this case row = 2 and col = 2.

When we print x:

print(x)

we will get:

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

which is what we want.

What is the logic behind this? Is [0 for i in range(row)] saying that, for every element in the range of the specified row number, we are going to assign a 0 to effectively create our first row in the matrix?

Then for j in range(col) is saying we repeat the creation of this list according to the specified column number to effectively create more rows, which end up being columns?

How should I be reading this code snippet from left to right?

like image 288
nvars Avatar asked Oct 25 '25 22:10

nvars


2 Answers

It is just a shortcut for this:

x = []
for j in range(column):
    _ = []
    for i in range(row):
        _.append(i)
    x.append(_)

you can put the inner for loop into one by saying that the list is composed of a whole bunch of 0's. We do that for each i in range(row), so we can say _ = [0 for i in range(row)]. This is how that looks:

x = []
for j in range(column):
    x.append([0 for i in range(row)])

We can now see that x is composed of a bunch of [0 for i in range(row)]'s and we do that once for each of j in range(column), so we can simplify it to this:

x = [[0 for i in range(row)] for j in range(column)]
like image 196
zondo Avatar answered Oct 27 '25 11:10

zondo


Sometime to expand all the one-liner shorthand code can help you understand better:

Basic

x = [i for i in range(somelist)]

Can be expanded into:

x = []
for i in range(somelist):
    x.append(i)

More Nested

x = [[0 for i in range(row)] for j in range(col)]

Can be expanded into:

x = []
for j in range(col):
    _ = []
    for i in range(row):
        _.append(0)
    x.append(_)
like image 25
Yeo Avatar answered Oct 27 '25 11:10

Yeo