Search code examples
pythonlistfor-loop2d

How to write a 2D list with increasing numbers using a for loop


I can write a 2d list using for loops with the same value inside like:

list = [[0 for x in range(4)] for y in range(4)]

and I get the result:

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

But how can i write something similar to get a result incrementing the numbers?

The output should be something like:

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]

Thanks!


Solution

  • You can use:

    cols = 4
    rows = 4
    [[x+y*cols for x in range(cols)] for y in range(rows)]
    

    Or, using numpy.arange:

    import numpy as np
    rows = 3
    cols = 5
    np.arange(rows*cols).reshape((rows, cols)).tolist()
    

    output:

    [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]