Today I Learned
Python Making a List
Integrated with loops
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Even with conditions in the for loop
[1, 3, 5, 7, 9]
Nested loops in a list
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
Another example of nested loops
[0, 0, 0, 1, 1, 1]
The article gives an example of how to flatten a matrix using this trick. Semantically, one would using
matrix is [[11, 12], [21, 22]]
flattened matrix is [1, 1, 2, 2]
which is obviously WRONG. The correct code is given by the author as
matrix is [[11, 12], [21, 22]]
flattened matrix is [11, 12, 21, 22]
The key is to write the nested loops in a list as the normal nested loops.
With this possible confusion, the author proposed a line breaking solution
matrix is [[11, 12], [21, 22]]
flattened matrix is [11, 12, 21, 22]
which significantly improved the readability.