5

So if

list={1,2,3}

then output should be

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

or in different order.

user
  • 1,877
  • 10
  • 19

5 Answers5

10

In version 10.4 you can use

Subsequences[{1, 2, 3}]

(* {{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}} *)
Simon Woods
  • 84,945
  • 8
  • 175
  • 324
  • 1
    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 03 '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 03 '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 03 '16 at 20:49
7

One way is this:

Catenate@Table[
  Take[list, {i, j}],
  {i, Length[list]}, {j, i, Length[list]}
  ]
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
7

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

RunnyKine
  • 33,088
  • 3
  • 109
  • 176
6
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}], {}]
kglr
  • 394,356
  • 18
  • 477
  • 896
  • 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 03 '16 at 08:46
2
in:= Subsets[list]
out:= {{},{1},{2},{3},{1,2},{2,3},{1,2,3}}
user
  • 1,877
  • 10
  • 19