Search code examples
functionfor-loopiterator

The interative status of a for loop inside a function


Say that we have this function:

def my_function:
    for i in some_iterable:
        do_something();

When I call this function inside another for loop:

for i in something:
    my_function()

Does the for loop in my_function() maintain the status of i or does the loop start from i = 0 each time the function is called? If latter is the case, how can I continue to iterate the for loop inside the function every time the function is called?


Solution

  • The i variable in your main loop and i variable inside my_function (let's call it i') are two different variables. After the end of function execution, you don't have an access to i', but you have access to i. If you would like to save the "end state" of i', you could consider using generators.

    https://realpython.com/introduction-to-python-generators/

    Another approach is to pass i' as an argument and return the end state.

    def my_function(start_i):
        # code using start_i
        return end_i