Matt
Matt

Reputation: 189

Passing only populated lists to for loop

I have four lists:

list1=[1,2,3,4,5,6,7,8,9]
list2=['a','b','c','d','e','f']
list3=['one','two','three','four','five','six','seven']
list4=[]

I am trying to run the following code to generate all possible products of the contents of these lists:

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

It works perfectly when the input is only list1, list2, and list3. However, giving an empty list as well produces a blank output. This is problematic, as one of these four lists will always be empty, and I cannot tell which it will be.

Is there a way of passing only the names of populated lists to the for loop? I am unsure of where to go with generator expressions, which I think is the likely answer here.

Upvotes: 0

Views: 29

Answers (1)

Sunitha
Sunitha

Reputation: 12015

Use filter to remove the empty list. You can use filter(bool, (list1,list2,list3,list4)) or filter(None, (list1,list2,list3,list4)) to filter the list

for i in itertools.product(*filter(bool, (list1,list2,list3,list4))):
    print(i)

Upvotes: 2

Related Questions