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!
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With