Skip to main content
1 of 2
Sascha
  • 8.5k
  • 2
  • 34
  • 66

Partition list into $n$ sublists

Is there an inbuilt function/option or an elegant composition of functions for partitioning a list into exactly $n$ sublists? I played around with Partition and its options but could not find anything suitable by itself. The general requirement is that the Length of the resulting splitted list is $n$. A few interesting corner cases:

  • Splitting a list into $n=1$ parts should result in the list wrapped with List, e.g. splitting {1,2,3} into $n=1$ parts yields {{1,2,3}} because Length[{{1,2,3}}] is 1
  • Splitting lists with fewer than $n$ elements by padding with empty lists e.g. {1,2}into $n=3$ parts should yield {{1}, {2}, {}}
  • Splitting lists of uneven length into an even number of parts or vice versa e.g. {1,2,3} into $n=2$ parts should either yield {{1,2},{3}} or {{1}, {2,3}}. It doesn't matter to me which, but behavior should be consistent.

Right now I use

ClearAll@splitList;
splitList[1][list_] := {list};
splitList[parts_Integer][list_] := 
  With[{n = Ceiling[Length[list]/parts]}, 
     Partition[list, UpTo[n]] // 
     Replace[
      {prev : Repeated[{___}, parts - 1]} :> 
      {prev, Apply[Sequence]@Table[{}, {parts - Length@{prev}}] } 
     ]
  ]

I feel that the concept of splitting a list into exactly $n$ sublists is something that is easy to express but involves difficult corner cases and thus could be something that is already implemented in Mathematica, much like with regular Partition and UpTo.

Sascha
  • 8.5k
  • 2
  • 34
  • 66