Combinations of multiple lists

Don't iterate over the same iterator multiple times, after the first time it's exhausted. Iterate over a fresh iterator each time:

for l1_iterator in itertools.combinations(list1, 5):
    for l2_iterator in itertools.combinations(list2, 2):
        for l3_iterator in itertools.combinations(list3, 3):
            sample = l1_iterator + l2_iterator + l3_iterator
            print(sample)

Or make lists of each one in advance to avoid recomputation:

l1_combinations = list(itertools.combinations(list1, 5))
l2_combinations = list(itertools.combinations(list2, 2))
l3_combinations = list(itertools.combinations(list3, 3))
for l1_iterator in l1_combinations:
    for l2_iterator in l2_combinations:
        for l3_iterator in l3_combinations:
            sample = l1_iterator + l2_iterator + l3_iterator
            print(sample)

As an alternative to regenerating the list of combinations, compute the product of the combinations up front; this also saves you from nesting for loops.

from itertools import combinations, product


list1 = list("abcdefgh")
list2 = list("ijk")
list3 = list("lmnop")

l1 = combinations(list1, 5)
l2 = combinations(list2, 2)
l3 = combinations(list3, 3)
for c1, c2, c3 in product(l1, l2, l3):
    sample = c1 + c2 + c3
    print(sample)

Tags:

Python