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
Itertools is a module in python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module incorporates functions that utilize computational resources efficiently.
Requirements. We must import the itertools module before we can use it. We will also import the operator module. This module is not necessary when using itertools , it is only needed for some of the examples below.
Introduction. itertools is a built-in module in Python for handling iterables. It provides a number of fast, memory-efficient way of looping through iterables to achieve different desired results.
itertools.product(.., repeat=n)
>>> import itertools
>>> list(itertools.product((0,1), 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)]
Python Module Index contains links for standard library modules documentation.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With