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?
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)]
Sometime to expand all the one-liner shorthand code can help you understand better:
x = [i for i in range(somelist)]
Can be expanded into:
x = []
for i in range(somelist):
x.append(i)
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(_)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With