0

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?

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78
  • In python, you can use a generator to continue iterating when the function is called https://stackoverflow.com/questions/1756096/understanding-generators-in-python – IronMan Dec 31 '20 at 00:55

1 Answers1

1

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
LightFelicis
  • 129
  • 1
  • 5