# All binary sequences with length n

I don't know if there is a built-in function for this, but I'm thinking about something like this

Outer[List, Table[{0,1},{n}] ]

But Outer doesn't accept this type of input. What should I do?

Tuples is surely better but you can make Outer work very simply too:

Outer[List, ##] & @@ Table[{0, 1}, {3}]
{{{{0, 0, 0}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}},
{{{1, 0, 0}, {1, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}}}

Also applicable is Array:

Array[List, {2, 2, 2}, 0]
{{{{0, 0, 0}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}},
{{{1, 0, 0}, {1, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}}}

Complete with flattening:

n = 4;
{Array[List, ConstantArray[2, n], 0, ## &]}
{{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 1, 1},
{0, 1, 0, 0}, {0, 1, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 1},
{1, 0, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 0, 1, 1},
{1, 1, 0, 0}, {1, 1, 0, 1}, {1, 1, 1, 0}, {1, 1, 1, 1}}

You could try Tuples:

Tuples[{0, 1}, 4]

(*
{{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1},
{0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1},
{1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1},
{1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}
*)

While Tuples works well for generating all of them at once, sometimes we need to enumerate them one by one, without keeping all previous results in memory. In this case you can use

Do[ ... IntegerDigits[k, 2, n] ...,  {k, 0, 2^n-1}]
• What does the ... do? I get a syntax error when I execute it. – DumpsterDoofus Jan 14 '15 at 19:47
• @DumpsterDoofus Nothing. It's not executable code, I meant that one might want to put other things in the Do loop. – Szabolcs Jan 14 '15 at 19:48
• @Dumps I use . . . for that purpose to reduce confusion with RepeatedNull; I'm not sure if it works. – Mr.Wizard Jan 14 '15 at 22:01
IntegerDigits[Range[2^5], 2, 5]

or as a function:

myList[n_: Integer] := Flatten[Array[List, Table[2, {n}], 0], n - 1]

But if you need to display the digits as a string rather than a comma-separated list:

StringJoin /@ Tuples[{"0", "1"}, 5]

$\left( \begin{array}{cccc} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 1 & 0 & 0 \\ 0 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 \\ 0 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 \\ 1 & 0 & 0 & 1 \\ 1 & 0 & 1 & 0 \\ 1 & 0 & 1 & 1 \\ 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 1 \\ 1 & 1 & 1 & 0 \\ 1 & 1 & 1 & 1 \\ \end{array} \right)$