return sub-lists contained in a list,fixed size

246 Views Asked by At

How could I get (in a very efficient python way), a group of sub-lists contained in another long list??, I explain with example:

Let's say I have this:

List = [[1,2,3],[4,5,6],[7,8,9],[2,4,3],......long list]

I would like to get an output grouping the sub-list in, let's say, in a groups of 7 sub-lists, then the output would be like:

L1 = [1,2,3]
L2 = [4,5,6]
L3 = [7,8,9]
up to L7
then process those 7 lists separately
and then start again....
L1 = [x,x,x] this L1 would be (obviously) the 8th sub-list in the big list "List"
L2 = [x,x,x] this would be the 9th sub-list....and so on

I dont know if I should call it like this but, It would be like making "chunks" of 7 sub-lists.

Is it possible in a fast and efficient way?

1

There are 1 best solutions below

2
On

You can do it with slicing. See Explain Python's slice notation for more details.

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

for i in range(0, len(list), 7):
  L1, L2, L3, L4, L5, L6, L7 = list[i:i+7]
  ...

Note: the length of the list must be a multiple of 7 to do this. If not, append as much as None s to make sure it is divisible by 7.