Conditional Nested Loop in Python

Viewed 705

I have a set of different conditions that will populate a list with either 1, 2 or 3 different sub-lists.

I'm looking for a way to write a condition that will either run:

  1. A single loop on elements in a single list
  2. A double loop on elements in both sublists
  3. A triple loop on elements in all 3 sublists

For example:

list1 = ['UK', 'USA', 'Austria', 'Canada']
list2 = ['001', '001', '99', '1001', '009', '002']
list3 = [100, 200, 300, 500, 1000]

list_total = [list1, list2, list3]

if list2 and list3 or list_total[1] and list_total[2] are both None:
   for elm in list1:
   ***do stuff***

if list2 or list_total[1] is None:
   for elm1 in list1:
   ***maybe do stuff if I want***
       for elm2 in list2:
       ***do stuff***

if all lists or list_total[1] and list_total[2] and list_total[3] are all not None:
   for elm1 in list1:
       for elm2 in list2:
       ***maybe do stuff if I want***
           for elm3 in list3:
           ***do stuff***

Is there any way to do this?

I can't just iterate over all elements in a list to 'create' a for loop from that I can see.

1 Answers

What you need is probably itertools.product.

Code example:

import itertools

list1 = ['UK', 'USA', 'Austria', 'Canada']
list2 = ['001', '001', '99', '1001', '009', '002']
# list3 = [100, 200, 300, 500, 1000]
list3 = None

list_total = [list1, list2, list3]

list_total = [l for l in list_total if l is not None]

for t in itertools.product(*list_total):
    print(t)

Hope you can go from here.

Related