0

I am trying to have a list restart itself from the beginning, once StopIteration exception is thrown or a certain point is reached but I'm having no luck.

Examples Below:

my_list = ["Test Subject 1", "Test Subject 2","Test Subject 3","Test Subject 4"]

my_lists = iter(my_list)

while True:
    print (next(my_lists))
    
    continue

Prints: Test Subject 1 Test Subject 2 Test Subject 3 Test Subject 4

However, I would like for this program to loop forever, until I stop it myself, each time returning to the first subject in the list.

I have tried the below to no avail:

my_list = ["Test Subject 1", "Test Subject 2","Test Subject 3","Test Subject 4"]

my_ListIter = iter(my_list)

while True:
    print(next(my_ListIter))
    if my_ListIter := (my_list[3]):
        my_ListIter = (my_list[0])
    continue

In a nutshell, once the script has gotten to the last point in the list or thrown the StopIteration exception, I want it to return to my_list[0] and start over again.

Is this possible?

Thanks a lot in advance for any help.

  • 3
    I think you're looking for [`itertools.cycle`](https://docs.python.org/3/library/itertools.html#itertools.cycle) function. – Chiheb Nexus Dec 01 '21 at 01:15
  • The *list* wouldn't be stopped or restarted, the *iterator* would. And no, iterators don't (really, *shouldn't*) be restarted once the raise StopIteration (although some built-in iterators do have thst behavior sorta, e.g. file iterators by seeking to the beginning in the underlying file cursor) – juanpa.arrivillaga Dec 01 '21 at 01:15

0 Answers0