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.
Is there a neat way to do it in Python?
An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__() .
We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list.
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'
The correct answer is to use itertools.cycle. But, let's assume that library function doesn't exist. How would you implement it?
Use a generator:
def circular(): while True: for connection in ['a', 'b', 'c']: yield connection
Then, you can either use a for
statement to iterate infinitely, or you can call next()
to get the single next value from the generator iterator:
connections = circular() next(connections) # 'a' next(connections) # 'b' next(connections) # 'c' next(connections) # 'a' next(connections) # 'b' next(connections) # 'c' next(connections) # 'a' #....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With