Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a 1D list into a 2D list with a given row length in python [duplicate]

Is there an easy way to convert a 1D list into a 2D list with a given row length?

Suppose I have a list like this:

myList =  [1, 2, 3, 4, 5, 6, 7, 8, 9]

I want to convert the above list into a 3 x 3 table like below:

myList = [[1,2,3],[4,5,6],[7,8,9]]

I know I can accomplish this by creating a new 2D list called myList2 and inserting the element into MyList2 using 2 nested for loops. Like MyList2[x][y] = myList[i] i++

I think there should be a better way to do it (without using external libraries or modules)

Thanks!

like image 317
Marlon C. Carrillo Avatar asked Jan 09 '23 07:01

Marlon C. Carrillo


1 Answers

Using list comprehension with slice:

>>> myList =  [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> n = 3
>>> [myList[i:i+n] for i in range(0, len(myList), n)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 145
falsetru Avatar answered Jan 11 '23 22:01

falsetru