Python Forum
Create Dynamic For Loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Create Dynamic For Loop (/thread-33448.html)



Create Dynamic For Loop - quest - Apr-26-2021

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?


RE: Create Dynamic For Loop - ndc85430 - Apr-26-2021

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.


RE: Create Dynamic For Loop - buran - Apr-26-2021

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.


RE: Create Dynamic For Loop - ibreeden - Apr-26-2021

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)