Cezar Cobuz
Cezar Cobuz

Reputation: 1207

How can I avoid duplicating code inside a for + if chain?

How can I avoid splitting the code in two separate parts? I am trying to call the "DoSomething_..." function just once but work in both scenarios. I might add more "for(s)" to this and the problem is that I have to handle to separate parts of code.

    for first in FIRST_LIST:
      for second in SECOND_LIST:
          for third in THIRD_LIST:
              if third!='Some specific thing':
                  for fourth in FOURTH_LIST:
                      DoSomething_K_x_fourth_Times(first,second,third,fourth)
              else:
                  forth=0
                  DoSomething_K_Times(first,second,third,fourth)

Upvotes: 3

Views: 108

Answers (2)

englealuze
englealuze

Reputation: 1663

  def DoSomething_K_Times(first,second,third,splitpoint):
      for x in splitpoint:
          ...

  for first in FIRST_LIST:
      for second in SECOND_LIST:
          for third in THIRD_LIST:
              if third != 'Some specific thing':
                  DoSomething_K_Times(first,second,third,FOURTH_LIST)
              else:
                  DoSomething_K_Times(first,second,third,[0])

Upvotes: 0

falsetru
falsetru

Reputation: 369134

Create a list with single item [0] or FOURTH_LIST depending on the condition, and iterate the list:

for first in FIRST_LIST:
    for second in SECOND_LIST:
        for third in THIRD_LIST:
            if third == 'Some specific thing':
                a_list = [0]
            else:
                a_list = FOURTH_LIST
            for fourth in a_list:
                DoSomething_K_x_fourth_Times(first, second, third, fourth)

UPDATE

Assign different function to a variable (func in the below code) depending on the condition, and call the function.

for first in FIRST_LIST:
    for second in SECOND_LIST:
        for third in THIRD_LIST:
            if third == 'Some specific thing':
                a_list = [0]
                func = DoSomething_K_x_fourth_Times
            else:
                a_list = FOURTH_LIST
                func = DoSomething_K_Times

            for fourth in a_list:
                func(first, second, third, fourth)

Upvotes: 2

Related Questions