I'd like to get the product of two lists. I can do this using itertools.product
:
from itertools import product
for i in product([1, 2], ['a', 'b']):
print(i, end='\t')
Gives:
(1, 'a') (1, 'b') (2, 'a') (2, 'b')
The problem is that one of the two lists could be empty. I just need to iterate over the non-empty list as a normal for loop in this case. Something like:
for i in something([1, 2], []):
print(i, end='\t')
To give:
1 2
The code works fine if I handle the exception at the beginning with many if
statements that checks for the lengths of the lists, and with the same code for every combination (list1
is empty, list2
is empty, none are empty), but this way I just wrote the same code 3 times:
from itertools import product
if not list1:
for i in list2:
print(i, end='\t')
elif not list2:
for i in list1:
print(i, end='\t')
else:
for i in product(list1, list2):
print(i, end='\t')
Is there a more elegant way to do so?