Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Dynamic For Loop
#1
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?
Reply
#2
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.
buran likes this post
Reply
#3
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop? JaneTan 1 1,901 Feb-28-2021, 06:20 PM
Last Post: Larz60+
  how to create pythonic codes including for loop and if statement? aupres 1 609 Jan-02-2021, 06:10 AM
Last Post: Gribouillis
  create loop of subplot plotly dash without hardcode tonycat 0 1,685 Sep-23-2020, 08:40 AM
Last Post: tonycat
  Create tempfile that use in loop for insert into DB Firsttimepython 2 822 May-29-2020, 04:15 PM
Last Post: Firsttimepython
  Create, assign and print variables in loop steven_tr 10 1,708 May-28-2020, 04:26 PM
Last Post: ndc85430
  Mysql CREATE TABLE IF NOT EXISTS dynamic table name nisusavi 0 795 Apr-29-2020, 06:45 PM
Last Post: nisusavi
  Create a dynamic Menu from a editable Dictionary. KiNeMs 1 862 Jan-28-2020, 04:27 AM
Last Post: Larz60+
  how to create subplots in for loop? python_newbie09 1 4,365 Sep-25-2019, 02:29 PM
Last Post: stullis
  How do I create a Dynamic Variable? Nwb 1 1,614 Jun-10-2018, 11:50 AM
Last Post: volcano63
  I can't figure out how to create variables in a while loop MrCag 1 1,264 May-08-2018, 08:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020