59

In Python, how can I get all combinations of n binary values 0 and 1?

For example, if n = 3, I want to have

[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ] #total 2^3 combinations 

How can I do this?

1
  • @eumiro, I think my question is also equivalent to this one, stackoverflow.com/questions/3252528/… , but that answer gives a string instead of a list. Commented Feb 18, 2013 at 8:52

3 Answers 3

106

Use itertools.product

import itertools lst = list(itertools.product([0, 1], repeat=3)) 

This will yield a list of tuples (see here)

You can easily change this to use a variable repeat:

n = 3 lst = list(itertools.product([0, 1], repeat=n)) 

If you need a list of lists, then you can use the map function (thanks @Aesthete).

lst = map(list, itertools.product([0, 1], repeat=n)) 

Or in Python 3:

lst = list(map(list, itertools.product([0, 1], repeat=n))) # OR lst = [list(i) for i in itertools.product([0, 1], repeat=n)] 

Note that using map or a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.product object and produce a list.

Sign up to request clarification or add additional context in comments.

7 Comments

+1 - map(list, product([0, 1], repeat=3)) will return the same format in case the OP is interested.
This is great, tuple is ok too.
@Volatility, just of curiosity, how do you know this? I had no clue how to find this function from the Python documentation.
@LWZ It comes with experience. (see point 6)
@Volatility, what a great post, thanks!
|
18

Without using any in-build functions or smart techniques we can get like this.

def per(n): for i in range(1<<n): s=bin(i)[2:] s='0'*(n-len(s))+s print (map(int,list(s))) per(3) 

output

[0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] [1, 1, 1] 

3 Comments

For me, this yields: <map object at 0x000001B30C760128> <map object at 0x000001B30C760048> <map object at 0x000001B30C760048> <map object at 0x000001B30C760048> <map object at 0x000001B30C760048> <map object at 0x000001B30C760048> <map object at 0x000001B30C760048> <map object at 0x000001B30C760048>
Have to call (list(map...)) to get actual lists out
Great idea! here is a simple version with format function: ``` def per(n): for i in range(1<<n): s="{:03b}".format(i) print(list(map(int, list(s)))) >>> per(3)
4

Following will give you all such combinations

bin = [0,1] [ (x,y,z) for x in bin for y in bin for z in bin ] 

3 Comments

He gives n=3 as an example only, so he wants to have this parametrized.
This works but n can't be large...
This wont scale!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.