Search code examples
pythonlistpython-itertools

Python: How do i use itertools?


I am trying to make a list containing all possible variations of 1 and 0. like for example if I have just two digits I want a list like this:

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

But if I decide to have 3 digits I want to have a list like this:

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

Someone told me to use itertools, but I cannot get it to work the way I want.

>>> list(itertools.permutations((range(2))))
[(0, 1), (1, 0)]
>>> [list(itertools.product((range(2))))]
[[(0,), (1,)]]

Is there a way to do this? And question number two, how would i find documentation on modules like this? I am just flailing blindly here


Solution

  • itertools.product() can take a second argument: the length. It defaults to one, as you have seen. Simply, you can add repeat=n to your function call:

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

    To find the docs, you can either use help(itertools) or just do a quick google (or whatever your search engine is) search "itertools python".