Python Forum

Full Version: Create Dynamic For Loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello
My number of sublists is in this line:

        number_of_sublist=sum(len(x) for x in incoming)
      
And I want to create a for loop till the this number. For instance if number_of_sublist=2, then I need to create 2 forloop:
for x in incoming:
         for y in x:

If number_of_sublist=4, then I need to create 4 for loop like that:
for x in incoming:
    for y in x:
       for z in y:
        for t in z:
...    
How can I do that in an efficient way?
You might want to look at the itertools module to see if anything there is useful. I don't know from your description whether product from that module is appropriate for you.
Also, note that number_of_sublists is sum of the number of elements in the sub_lists, it's not the number of sublists, that would be len(incoming)

>>> incoming = [[1, 3], [2, 5]]
>>> sum(len(x) for x in incoming)
4
>>> len(incoming)
2
And from your example it looks like you want the levels of depth (i.e. how much levels of nested lists you have). So best would be to show actual example of incoming and what you want to achieve.
For a variable number of nested loops you could go recursive.
def nested_loop(incoming, number_of_sublists):
    for x in incoming:
        if number_of_sublists > 0:
            nested_loop(x, number_of_sublists - 1)