I would like to iterate cyclically over a list (or any other iterable for that matter), and I know you can do this with the cycle
function from itertools
(as shown here), but this function loops indefinitely. I was wondering if there's a smart way to do this only once (and without using the modulo operator).
What I mean is that I would like to iterate over an iterable in such a way that the last item is the first one. So I would like to start iterating and stop whenever the iterator reaches the beginning of the iterable.
Something like this but less ugly:
points = [1, 2, 3, 4, 5]
start = points[0]
iterator = cycle(points)
p = next(iterator)
while True:
print(p)
p = next(iterator)
if p == start:
print("quitting at", p)
break