Home > Back-end >  How to write a 2D list with increasing numbers using a for loop
How to write a 2D list with increasing numbers using a for loop

Time:01-07

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 increaming 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!

CodePudding user response:

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]]

CodePudding user response:

You can achieve that with this list comprehension:

L = [[x for x in range(y,y 4)] for y in range(0,16,4)]

CodePudding user response:

You can achieve it like this :

l = [[x   3*y  y  for x in range(4)] for y in range(4)]
  •  Tags:  
  • Related