Search code examples
pythonpython-3.xfor-loopcoding-style

What is a good Pythonic way to handle complicated for loops with many functions?


I have a relatively complicated script that requires functions to be executed within a for loop and in some cases the result of one function is read into the next function. I can handle this relatively easy with a for loop, but the execution speed is significantly less than with list comprehension. I am not sure how to execute this problem with list comprehension. Is there a better vectorized way to do this in python. I am attaching an example that is significantly simpler than my actual problem, but it I think it highlights the problem. Any thoughts would be appreciated.

def func1(i):
    return i + 1

def func2(j):
    return j + 2

def func3(k):
    return k + 3

class test:
    def __init__(self, one, two, three):
    self.one = one
    self.two = two
    self.three = three

if __name__ == "__main__":

    obj = []
    for i in range(10):
        if i !=3 and i != 7:
            value1 = func1(i)
            value2 = func2(i)
            value3 = func3(value2)
            one1 = value1 + value2
            two1 = value1 + value2 + value3
            three1 = value1 + value3
            obj.append(test(one1, two1, three1))

Solution

  • Just cram the inside of your loop into its own function.

    def loop_interior(i):
            value1 = func1(i)
            value2 = func2(i)
            value3 = func3(value2)
            one1 = value1 + value2
            two1 = value1 + value2 + value3
            three1 = value1 + value3
            return test(one1, two1, three1)
    

    Now the loop populating obj is short and sweet. You could even use a list comprehension if you like. obj = [loop_interior(i) for i in range(10) if (i != 3 and i != 7)]