0

In python 3.8.6 I want to create an iterator which starts again from the beginning if all elements are used. So the list should repeat indefinitely.

Example code, raises StopIteration.

myiter = iter(["r", "g", "b", "m", "c", "k"])
for _ in range(100):
    print(next(myiter))

Of course I can implement it as follows:

mylist = ["r", "g", "b", "m", "c", "k"]
counter = 0
for _ in range(100):
    print(mylist[counter])
    counter += 1
    if counter==len(mylist):
        counter = 0

but it does not look very pythonic. Is there a better solution?

Alex
  • 41,580
  • 88
  • 260
  • 469

0 Answers0