Can I add a variable name to itertools list?

Viewed 95

This will print all of the possible combinations:

import itertools
iterables = [[0,1,2], ["3","46","5"]]
for item in itertools.product(*iterables, repeat=1):
    print(item)

like:

0,3
0,46
0,5
1,3
etc.

Suppose "A" has the values [0,1,2] and "B" has ["3", "46", "5], can I modify the code that the print will be something like:

A 0
B 3
A 0
B 46
A 1
B 3

etc.?

or any other way where the variable name is also part of the results?

Many thanks.

1 Answers

Flatten the list of tuples, and zip it with the repeating sequence of explicit variable names.

from itertools import chain, cycle, product

for var, value in zip(cycle(["A", "B"]),
                      chain.from_iterable(product(*iterables))):
    print(var, value)

chain.from_iterable turns something like (x, y), (x, y) into x, y, x, y. cycle([x,y]) produces x, y, x, y, .... The cycle is infinite, but zip only consumes as much as needed to exhaust the flattened product sequence.

Related