Search code examples
pythonlist2d

Create 2d list from 1d list with given length and width?


How to create 2D list from 1D list with given row and cols?

Given:

sample_list=[5, 2, 3, 4, 1, 6, 1, 6, 7, 2, 3]

row=2
cols=4

It should return this:

[[5, 2, 3, 4],[1, 6, 1, 6]]

I don't need other numbers = 7, 2, 3. I just want a list that has row and cols which user gives. My solution does not return what i want,

My solution:

def 1D_to_2D(sample_list, row, cols):
    return [sample_list[i:i+cols] for i in range(0, len(sample_list), rows)]

returns:

[[5, 2, 3, 4], [3, 4, 1, 6], [1, 6, 1, 6], [1, 6, 7, 2], [7, 2, 3], [3]]

Anyone can help?


Solution

  • Just slice your list using a list comprehension with range and a step of cols (not rows as you used), and limit the number of items using external slicing with rows:

    sample_list=[5, 2, 3, 4, 1, 6, 1, 6, 7, 2, 3]
    rows=2
    cols=4
    
    result = [sample_list[x:x+cols] for x in range(0,len(sample_list),cols)][:rows]
    

    result:

    [[5, 2, 3, 4], [1, 6, 1, 6]]