Search code examples
pythonpython-3.xiteratorlistiterator

Python: How to recall position after break from iteration over start, stop, step loop


I am learning about iterators and how to use them and in the process have come up with a question. Is it possible to recall where a loop left off during iteration (if the loop were to have a break condition that was met) and then to pick up from the recalled spot?

An example of what I am saying is, I have this code:

print("Range() Test")
for i in range(10, 100, 10):
    if i == 60:
        print('Break Point')
        break
    print(i)
for i in range(10, 100, 10):
    print(i)

Which should run and give you something like this:

Range() Test
10
20
30
40
50
Break Point
10
20
30
40
50
60
70
80
90

My first question is:

1) Is there a way to recall the position where the break took place and begin from there as opposed to my bumbling start-over? I have seen instanced where the iteration was over a list of items, but have not been able to find an example/work out a functioning example of using iter() on the start/stop/step notation.

2) In doing research (I am learning Python and doing a lot of self-teaching) I have seen the range() function describer both as an iterator and NOT as an iterator so, if anyone has more definitive information on this, as opposed to tearing me a new one for using it in my example, that would be much appreciated.

Thanks!


Solution

  • For your first question... I think you are on the right track. The iter() will make the range object an iterator. It will track itself and you can pick up where you were later in your code.

    >>> x=iter(range(1,100,10))
    >>> for i in x:
    ...     if i >30:
    ...             break
    ...
    >>> for i in x:
    ...     print(i)
    ...
    41
    51
    61
    71
    81
    91

    2) range objects are not iterators This Does a great job of explaining