Search code examples
pythonpython-2.7python-itertools

Interact with Each Iteration of itertools.product


I'm using the product method from the itertools python library to calculate all permutations of items in a list of lists. As an example:

>> elems = [[1,2],[4,5],[7,8]]
>> permutations = list(itertools.product(*elems))
>> print permutations
# this prints [(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8)]

How can I check each permutation as it is calculated, rather than returning the entire set of permutations at once? The problem I am currently facing is that I run into a python Memory Error while running my script because too many permutations are being generated. I only care about a single one of the permutations. If I can check each permutation as it is generated, I can store just a single value rather than storing every possible permutation. Is this possible, and if so, how would I go about implementing this?


Solution

  • You can just do it in a for loop, one at a time:

    for a_perm in itertools.product(*elems):
        print(a_perm)
    

    itertools.product() gives you iterator, which you can iterate over one item at a time.