2

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

JMzance
  • 1,704
  • 4
  • 30
  • 49
  • possible duplicate of [Python code to pick out all possible combinations from a list?](http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list) – vaultah Jan 03 '15 at 18:11
  • did you have a bit search already ? – Mazdak Jan 03 '15 at 18:12
  • Yeah ofc! Combinations doesnt work since order *is* important, however permutations will duplicate things like 1001 4 times. – JMzance Jan 03 '15 at 18:13
  • 1
    By "all possibly length n combinations", are you really trying to describe the Cartesian product? – DSM Jan 03 '15 at 18:14
  • No since the cartesian product of a list [0,1] would be 00, 01, 10, 00 right? And I would like, for example 4 items...Though maybe I could do this by taking the product of 4 lists? – JMzance Jan 03 '15 at 18:17
  • The product of `[0,1]` with *itself* would be those four elements (really pairs), but as you've guessed, `itertools.product` has a `repeat` argument for exactly this use case. – DSM Jan 03 '15 at 18:18

2 Answers2

9

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
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
0

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)]
Amit Kumar Gupta
  • 17,184
  • 7
  • 46
  • 64