# Partitioning lists by length of sublists

Suppose we have the following list

data = {{1, 2, 3}, {4, 3, 2, 1, 0}, {6, 7, 8}, {-5, -4, -3, -2, -1},
{-2, -3, -4}, {1, 1, 1, 1, 1}}


As we can see, some of the sublists have 3 elements, while others have 5 elements. I want the following: create two new lists lts3 and lst5 one with the 3-elements sublists and the other with all the 5-elements sublists.

lst3 = {{1, 2, 3}, {6, 7, 8}, {-2, -3, -4}};
lst5 = {{4, 3, 2, 1, 0}, {-5, -4, -3, -2,- 1}, {1, 1, 1, 1, 1}}


Any ideas?

• You are no newbie around here (>100 Q´s) -- do you really have no clue as how to go about that? – Yves Klett Oct 17 '16 at 11:43
• @YvesKlett I see your point. Surely I can find a way to solve this issue but I'm always looking for new elegant and quick solutions. – Vaggelis_Z Oct 17 '16 at 11:46

GatherBy[exp, Length] would work. Here exp is the expression.

In recent versions I would turn to GroupBy for this:

GroupBy[data, Length] /@ {3, 5}


Note: Lookup can be somewhat faster than Map.

If memory consumption is a concern consider using the older Sow and Reap as you can preselect the targets, e.g. Reap[Sow[#, Length@#] & ~Scan~ data, {3, 5}][[2, All, 1]] See Defining Tags in Reap.

• GroupBy is a nice function. This made me think of you :) – ubpdqn Oct 18 '16 at 8:54
• @ubpdqn I guess that makes me forgotten bastard? ;-) -- thanks for the laugh. :^) – Mr.Wizard Oct 18 '16 at 10:03
• Nice use of tags in Sow, thanks for that! – AndreasP Oct 18 '16 at 11:09
{lst3, lst5} = GatherBy[data, Length];


A simple approach is to use Select:

lst3 = Select[data, Length[#] == 3 &]


and

lst5 = Select[data, Length[#] == 5 &]