JMzance
JMzance

Reputation: 1746

Generating all possibly length n combinations of two items in python

I am trying to generate a list of length n from two possible items. e.g. One example could be, a list of length 4 comprising zeros or ones which would be 0000, 0001, 0010, 0100, 1000, 1001, etc. Thanks in advance, Jack

Upvotes: 3

Views: 1890

Answers (2)

Lev Levitsky
Lev Levitsky

Reputation: 65791

With itertools.product:

In [1]: from itertools import product

In [2]: list(product((0, 1), repeat=4))
Out[2]: 
[(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 can also just print ints as binary strings:

In [3]: for i in range(2**4):
   ...:     print('{:04b}'.format(i))
   ...:     
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

Upvotes: 10

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 18567

Check out the product function from the itertools module: https://docs.python.org/2/library/itertools.html#itertools.product

from itertools import product

product(range(2), repeat=4)
# --> <itertools.product object at 0x10bdc1500>

list(product(range(2), repeat=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)]

Upvotes: 0

Related Questions