Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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}}

share|improve this question
add comment

1 Answer

up vote 9 down vote accepted

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...)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.