Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading