Search code examples
pythonpython-itertools

How do I handle empty lists in nested for loops?


I am looking for a way to iterate through the product of two lists that can sometimes be empty. I was going to use itertools.product for that, so it would look like this:

import itertools

list1 = [1, 2]
list2 = ['a', 'b']

for i, j in itertools.product(list1, list2):
    print(i, j)

We would get:

1 a
1 b
2 a
2 b

And that's what I expect. But when one of the lists is empty, the loop won't print anything:

list1 = [1, 2]
list2 = []
    
for i, j in itertools.product(list1, list2):
    print(i, j)

Whereas I would like it to behave as if there was just one list. So, using itertools, do the equivalent of:

for i in itertools.product(list1):
    print(i)

which would have returned:

(1,)
(2,)

I could put this into a long if statement, but I am looking for a simple tweak that would easily scale if the number of lists increased. Thanks for your help.


Solution

  • Put them in one variable and filter them to use only the non-empty ones:

    import itertools
    
    lists = [1, 2], []
    
    for i in itertools.product(*filter(bool, lists)):
        print(i)
    

    Or if having them in separate variables is truly what you want:

    import itertools
    
    list1 = [1, 2]
    list2 = []
    
    for i in itertools.product(*filter(bool, (list1, list2))):
        print(i)
    

    Output of both:

    (1,)
    (2,)