How to partition a list and leave in the last sublist which is of different length?
In[75]:= Partition[{1,2,3,4,5},2]
Out[75]= {{1,2},{3,4}}
I want it to be
{{1,2},{3,4},{5}}
How to partition a list and leave in the last sublist which is of different length?
In[75]:= Partition[{1,2,3,4,5},2]
Out[75]= {{1,2},{3,4}}
I want it to be
{{1,2},{3,4},{5}}
You can use the additional arguments of Partition to achieve this result. The first 5 arguments of Partition are (see the docs for more info):
list: The list to be partitionedn: Length of the sublists (except perhaps for sublists with insufficient elements). Should be less than Length@listd: Partition offset. By default this is the same as n (no overlaps). A smaller value will result in overlaps of n-d samples and a larger value will result in skipping of d-n samples after every n samples.{kL, kR}: Determines whether overhangs are allowed at the beginning or the end of the listx: If overhangs are allowed, sublists with insufficient elements are padded with x.Using the above, you can get your desired output with:
Partition[{1, 2, 3, 4, 5}, 2, 2, {1, 1}, {}]
(* {{1, 2}, {3, 4}, {5}} *)
{1, 2, 3, 4, 5} to {{1, 2}, {3, 4, 5}}, or {1,2,3,4,5,6,7,8} to {{1,2,3},{4,5,6,7,8}}. Thanks.
– xslittlegrass
Oct 22 '14 at 01:55
list /. {h___List, p_List, l_List} :> {h, p ~Join~ l}
– rm -rf
Oct 22 '14 at 02:56
A useful Manipulate can help understanding how Partition works. It also provides the code to use for a certain partitioning.
Manipulate[
Grid[{
{"original list:", Range[n]},
{},
{"without offset:", Partition[Range[n], part]},
{"code:", Style[With[{n = n, part = part}, HoldForm@Partition[Range[n], part]], Bold]},
{},
{"with offset:", Partition[Range[n], part, offset, pos, pad]},
{"code:", Style[With[{n = n, part = part, offset = offset, pos = pos, pad = pad},
HoldForm@Partition[Range[n], part, offset, pos, pad]], Bold]}
}, Alignment -> {{Right, Left}}, Spacings -> {1, 1}],
Item[Style["Understanding Partition", FontFamily -> "Helvetica", Bold, 18]],
Delimiter,
{{n, 9, "length"}, 0, 20, 1, Appearance -> "Labeled"},
{{part, 1, "partition size"}, 1, 20, 1, Appearance -> "Labeled"},
{{offset, part, "offset"}, 1, part, 1, Appearance -> "Labeled"},
{{pos, {1, 1}, "position"}, {{1, -1}, {1, 1}, {-1, -1}, {-1, 1}}, ControlType -> SetterBar},
{{pad, "X", "padding with"}, {{} -> "{}", 0, 1, a, "X", Graphics[{Blue, Disk[]}, ImageSize -> 12]}, ControlType -> SetterBar}
]

Partition[{1, 2, 3, 4, 5}, 2, 2, {1, 1}, {}]– rm -rf Dec 16 '12 at 16:39Partitiondocs fully to find it, otherwise it's not obvious thatPartitioncan even do this. I would not close or delete the question, but post the answer instead. – Szabolcs Dec 16 '12 at 17:38