Search code examples
pythonpython-itertools

How to find itertools product of tuples in a list of unknown length?


I'm working on a program in which I'm using itertools.product() to find combinations of n number of tuples. For example:

n = int(input())

Let's say the user inputs 3

a = [(True, False), (True, False), (False, True)]

Now I want to get the following as the output:

[(True, True, True),
 (True, True, False),
 (True, False, True),
 (True, False, False),
 (False, True, True),
 (False, True, False),
 (False, False, True),
 (False, False, False)]

I can do this when the number of tuples in the list is specified.


Solution

  • Product works the following:

    >>> list(itertools.product([True, False], [True, False]))
    [(True, True), (True, False), (False, True), (False, False)]
    >>> list(itertools.product([True, False], [True, False], [True, False]))
    [(True, True, True),
     (True, True, False),
     (True, False, True),
     (True, False, False),
     (False, True, True),
     (False, True, False),
     (False, False, True),
     (False, False, False)]
    

    So what you need to do is

    import itertools
    
    n = int(input())
    a = [(True, False) for i in range(n)]
    list(itertools.product(*a))