-1

I have a list of numbers:

L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

I found how to create a list of lists:

new_L = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]]

But that is not what I need. I need to create (x) times (y) list of lists. For example, as a 3 times 4 list of lists:

new_L_2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Or a 2*6 list of lists:

new_L_3 = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

How can I make it? Thanks in advance.

Irfan wani
  • 4,084
  • 2
  • 19
  • 34
Stockfish
  • 144
  • 8
  • 1
    Use a list comprehension which uses slices. Seems like homework. What have you tried? Where are you stuck? – John Coleman Feb 24 '21 at 11:41
  • I think this question may have already been answered [here](https://stackoverflow.com/questions/12293208/how-to-create-a-list-of-lists) – Hunter Feb 24 '21 at 11:42
  • using numpy [list to 2d array](https://stackoverflow.com/questions/12575421/convert-a-1d-array-to-a-2d-array-in-numpy) – sahasrara62 Feb 24 '21 at 11:44

3 Answers3

2

You can use list comprehension with range to get x number of element. For example you want 4 elements use

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
out = [l[i: i+4] for i in range(0, len(l), 4)]

print(out)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Epsi95
  • 8,832
  • 1
  • 16
  • 34
1

Think about how you would break this down if you were to draw it out on paper.

You need to create a function that iterates through a list of numbers. There a plenty of ways to do this, but one from the top of my head is as follows.

Create a function that takes an input list and an integer (X) for how many items in each sub-list. Iterate through each item in the list and add it to a temporary list. If the index of the list item is divisible by X, append the temporary list to the list of lists, empty the temporary list, and start again.

Kane
  • 31
  • 6
0
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
x = 3
y = 4

newList = []

for i in range(x):
    newList.append([L[t+(i*y)] for t in range(y)])

print(newList)
Wrench
  • 490
  • 4
  • 13