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?