# Using Partition to allow sublists of different lengths

As a minimal example, suppose I have a list of the integers from 1 to 25. Suppose I want to use Partition to partition the list into sublists of length 10 but without dropping the "end" elements.

For example, this code

list = Range[1, 25];
Partition[list, 10]


gives: {{1,2,3,4,5,6,7,8,9,10},{11,12,13,14,15,16,17,18,19,20}}, where the integers 21 through 25 have been dropped. What if I want to keep those integers? I would like Partition to partition the list into sublists of length 10 only when possible (i.e., keeping the "end" elements). How can I do this?

In the Partition documentation, this entry looks like a possibility:

Partition[list, n, d, {kL, kR}, {}] uses no padding, and so can yield sublists of different lengths.

So I tried:

Partition[list, 10, 0, {1, 1}, {}]

but this did not work (according to the documentation {kL, kR} = {1, 1} means "allow maximal overhang at the end").

On the other hand, this seems to work:

Partition[list, 10, 10, 1, {}]


which gives the correct output: {{1,2,3,4,5,6,7,8,9,10},{11,12,13,14,15,16,17,18,19,20},{21,22,23,24,25}}.

Is this the best way to solve the problem, or am I making a conceptual mistake? I obtained the idea Partition[list, 10, 10, 1, {}] from the following documentation, but conceptually I am not really sure what it is doing:

Use no padding, so later sublists can be shorter: Partition[{a,b,c,d,e,f,g},3,3,1,{}]

{{a,b,c},{d,e,f},{g}}

• Related: (28416), (128133) Oct 21, 2016 at 4:27

Yes, this is the correct syntax:

Partition[list, 10, 10, 1, {}]


The fourth argument is a short form of {1, 1} so the full form is:

Partition[list, 10, 10, {1, 1}, {}]


As the documentation says:

Partition[list, n, d, {kL, kR}]
specifies that the first element of list should appear at position kL in the first sublist, and the last element of list should appear at or after position kR in the last sublist. If additional elements are needed, Partition fills them in by treating list as cyclic.

You need the arguments 10, 10 because this means lengths of ten without overlap. (Take 10, move over ten, take another ten...)

Since Mathematica 10.3, we can use the much more convenient UpTo:

Partition[Range[25], UpTo[10]]
(* {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}} *)

• Does UpTo work in Part? Oct 21, 2016 at 4:26
• @Mr.Wizard No, but it works in Take. What do you want to do with it? Oct 21, 2016 at 11:38
• I was just curious. I like to use Part a lot so I wondered if something like foo[[ ;; UpTo[5] ]] would work. It may be best that it does not as that could add overhead to every Part call. Oct 21, 2016 at 12:12

Just to show InternalPartitionRagged:

r = Range[25];
qr[m_, n_] :=
Module[{a = QuotientRemainder[m, n]},
Table[n, {a[[1]]}]~Join~{a[[2]]}]
InternalPartitionRagged[r, qr[25, 10]]


yields:

{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {11, 12, 13, 14, 15, 16, 17, 18, 19,
20}, {21, 22, 23, 24, 25}}