Python quickie: using `itertools.product` to generate binary strings

March 18, 2011 at 04:08 PM | Python | View Comments

Problem: you need to enumerate the binary strings between 000 and 111 (ie, 000, 001, 010, …).

Solution: itertools.product:

>>> from itertools import product
>>> for bits in product([0, 1], repeat=3):
...     print "".join(str(bit) for bit in bits)
...
000
001
010
011
…
>>>

For more like this, check out Raymond Hettinger's (really good) talk Fun with Python's Newer Tools, from PyCon 2011.