Fix Python – Circular list iterator in Python


Asked By – user443854

I need to iterate over a circular list, possibly many times, each time starting with the last visited item.

The use case is a connection pool. A client asks for connection, an iterator checks if pointed-to connection is available and returns it, otherwise loops until it finds one that is available.

How can I do this neatly in Python?

If you instead need an immediately created list of the results up to a certain length, rather than iterating on demand: see Repeat list to max number of elements for general techniques, and How to replicate array to specific length array for Numpy-specific techniques.

Now we will see solution for issue: Circular list iterator in Python


Use itertools.cycle, that’s its exact purpose:

from itertools import cycle

lst = ['a', 'b', 'c']

pool = cycle(lst)

for item in pool:
    print item,


a b c a b c ...

(Loops forever, obviously)

In order to manually advance the iterator and pull values from it one by one, simply call next(pool):

>>> next(pool)
>>> next(pool)

This question is answered By – Lukas Graf

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0