Circular list iterator in Python

iterator, list, python

Solution

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)

Output:

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)
'a'
>>> next(pool)
'b'

Problem

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.

Original source

Related problems