Combining multiple lists to obtain integers for given condition

Let us suppose I have 3 lists with each of them has random numbers ranging from (0-9)

digit_0 = [0, 1, 2, 3, 5, 8]
digit_1 = [1, 2, 3, 8, 9]
digit_2 = [3, 4, 6, 7]

I want to create all the possible numbers for 3 -digit number ABC, such that A can only take values from digit_0, B can only from digit_1 and C can only from digit_2 arrays

The simplest solution seems to be creating 3 loops

for A in digit_0:
    for B in digit_1:
        for C in digit_2:

However, I am wondering is there a more effective solution ?

Answer

Use itertools.product:

from itertools import product

digit_0 = (0, 1, 2, 3, 5, 8)
digit_1 = (1, 2, 3, 8, 9)
digit_2 = (3, 4, 6, 7)

for digits in product(digit_0, digit_1, digit_2):
    print(''.join(map(str, digits)), end=' ')

Output:

013 014 016 017 023 024 026 027 033 034 036 037 083 084 086 087 093 094 096 097 113 114 116 117 

It would be even better to put your tuples in a list, rather than giving them ressembling names:

from itertools import product

digit_choices = [(0, 1, 2, 3, 5, 8), (1, 2, 3, 8, 9), (3, 4, 6, 7)]

for digits in product(*digit_choices):
    print(''.join(map(str, digits)))

and this will make it easy to generate combinations with any number of digits.