# How can one get all possible sublists of a list? [duplicate]

So if

list={1,2,3}


then output should be

{{},{1},{2},{3},{1,2},{2,3},{1,2,3}}


or in different order.

In version 10.4 you can use

Subsequences[{1, 2, 3}]

(* {{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}} *)

• For some reason, the built-in gets quite slower for larger inputs. Timings here. (Also, I find the behaviour to return the empty list once really inconsistent, but apparently that's what the OP wants.) – Martin Ender Apr 3 '16 at 18:52
• @MartinBüttner, regarding the linked question RunnyKine's answer here gives four empty lists if you remove the Union bit. – Simon Woods Apr 3 '16 at 19:44
• Yes, I'm aware. :) I'll probably update my answer some time this week with additional approaches, Catenate @ instead of Join @@ and new timings. – Martin Ender Apr 3 '16 at 20:49

One way is this:

Catenate@Table[
Take[list, {i, j}],
{i, Length[list]}, {j, i, Length[list]}
]

• This is actually the fastest solution (although I should definitely update my post to use Catenate@ instead of Join@@, because the latter is a bit slower). – Martin Ender Apr 3 '16 at 18:51

One can use SequenceCases starting from version 10.1:

Union@SequenceCases[{1, 2, 3}, {___}, Overlaps -> All]


{{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}}

Or, if you don't want the empty list:

SequenceCases[{1, 2, 3}, {__}, Overlaps -> All]


{{1, 2, 3}, {1, 2}, {1}, {2, 3}, {2}, {3}}

Sort[Join[{{}}, ReplaceList[list, {___, x__, ___} :> {x}]]]


{{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}}

Also:

ClearAll[f]
f[lst_] := With[{indices = List /@ Join @@ (Partition[Range[Length@lst], #, 1] & /@
Range[Length@lst])}, Extract[lst, indices]]

f[{a, b, c, d}]


{{a}, {b}, {c}, {d}, {a, b}, {b, c}, {c, d}, {a, b, c}, {b, c, d}, {a, b, c, d}}

If you need to include {}:

Prepend[f[{a, b, c, d}], {}]

• Ah, this is better than mine! About the empty {}, notice that the OP added that to the question only after he posted his own answer with Subsets ... which doesn't return what he asked for even after this update to the question. – Szabolcs Apr 3 '16 at 8:46
in:= Subsets[list]
out:= {{},{1},{2},{3},{1,2},{2,3},{1,2,3}}

• That doesn't return what you asked for. Do you want all subsets, including {1,3} or do you want all sublists of contiguous elements as your example suggests? – Szabolcs Apr 3 '16 at 8:35
• @Szabolcs Nice point! – hxiao Apr 3 '16 at 8:41
• And do you want the empty set or not? (Your original post suggested that you did not) – user1066 Apr 3 '16 at 9:14