Janek Ziobro
Janek Ziobro

Reputation: 97

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.

Upvotes: 0

Views: 447

Answers (2)

user11718531
user11718531

Reputation:

One way of doing it would be checking if any of the lists is empty and putting in some value, but this is not the most elegant solution. For example:

import itertools

list1 = [1, 2]
list2 = []

if len(list2) == 0:
    list2.append("")

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

Upvotes: 2

Pychopath
Pychopath

Reputation: 1580

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,)

Upvotes: 3

Related Questions