0

Here's a list like this.

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

I want to split this list every 4 intervals.

In other words, I want to make it like this.

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

I want to divide the list and save it.

Is there a function that provides this partitioning capability?

ddjfjfj djfiejdn
  • 131
  • 1
  • 12

2 Answers2

1
for i in range(len(mylist)):
  if(i+1)%4 == 0:
    print(mylist[i-3:i+1])

Parijat Bhatt
  • 664
  • 4
  • 6
0

You can use zip and iter like this, to split the list into sublists

>>> mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> list(zip(*([iter(mylist)]*4)))
[(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)]
>>> 
>>> list(map(list, zip(*([iter(mylist)]*4))))
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Sunitha
  • 11,777
  • 2
  • 20
  • 23