Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I was just thinking how Tuples was created so , I came up with this,

Flatten[Outer[List, {a, b}, {a, b}, {a, b}], 2] == Tuples[{a, b}, 3]


Now, I want to convert it to a function,

fun[x_List] := Block[{}, Flatten[Outer[List, x], Length[x] - 1]]

But the problem is the I need to put this List as a sequence but I am not finding a work around.

share|improve this question
Just a wild guess: {a, b, c} /. List -> Sequence does something like this work? – bobthechemist Mar 17 '14 at 17:29
I generally don't face it, in fact I have answered 2-3 questions that used it, but I don't know what the problem is. It is converting all sublists to sequences. – Rorschach Mar 17 '14 at 17:33
@bobthechemist it certainly does! – Aron May 29 '14 at 17:41
up vote 5 down vote accepted

You can use SlotSequence and ConstantArray (or Table):

fun[x_List, n_Integer] := Flatten[Outer[List, ##] & @@ ConstantArray[x, n], 2]

fun[{a, b}, 3] == Tuples[{a, b}, 3]
(* True *)
share|improve this answer
I tried using slotsequence,looks like I wasn't getting the syntax right. Thanks :) – Rorschach Mar 17 '14 at 17:41
Good example of SlotSequence, which I never seem to think of. – DavidC Mar 17 '14 at 17:48

Here's an approach with Table.

fun[x_List, n_Integer] := Flatten[Outer[List, Sequence @@ Table[x, {n}]], n-1]


fun[{a, b}, 3]

{{a, a, a}, {a, a, b}, {a, b, a}, {a, b, b}, {b, a, a}, {b, a, b}, {b, b, a}, {b, b, b}}

fun[{a, b}, 4]

{{a, a, a, a}, {a, a, a, b}, {a, a, b, a}, {a, a, b, b}, {a, b, a, a}, {a, b, a, b}, {a, b, b, a}, {a, b, b, b}, {b, a, a, a}, {b, a, a, b}, {b, a, b, a}, {b, a, b, b}, {b, b, a, a}, {b, b, a, b}, {b, b, b, a}, {b, b, b, b}}

share|improve this answer
Apply seems a good option to. But using {{a,b},{c,d}}/.List->Sequence should be applied only once as a replace once rule, but it goes down the list generating Sequence[a, b, c, d] – Rorschach Mar 17 '14 at 17:56
Hmmm. I wasn't aware of that. I'll try to fix it. – DavidC Mar 17 '14 at 19:50

Your Answer


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.