Is there a way use itertools.product as a list?

Question:

The title might not be worded the right way, but I’ve got a function that takes a list as an input and outputs a value. Let’s say I want to iterate the function over all possible combinations of a binary list of a given length, n. I know that (itertools.product([0,1], repeat=n) is the best way to handle all combinations, but an itertools object creates each different combination as a tuple, not a list. So in order to feed them into the function, they each need to be converted to a list, which now negates the effectiveness of using itertools.

Is there any way around this? An alternative to, or way to manipulate, the itertools function that allows each entry to act as a list? Or is the only way to alter the initial function to take tuples instead of lists?

My primary desire for this is to combine the properties of a list with the generative properties of itertools. I would prefer to find a fix like this that minimizes compute resources, as opposed to re-writing the rest of my code for the sake of modularity that I may not fully utilize.

Asked By: YaGoi Root

||

Answers:

If the function must take a list, you can convert the individual combinations to a list when needed. You still get the benefits of product, i.e., you’re not storing all the combinations in memory at any given point, you’re only converting one combination to a list at a time.

for combination in itertools.product([0,1], repeat=n):
    function_that_must_take_a_list(list(combination))
Answered By: joanis