Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular list iterator in Python

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?

like image 206
user443854 Avatar asked May 01 '14 20:05

user443854


People also ask

What is list iterator 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__() .

Can we iterate list in Python?

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.


2 Answers

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' 
like image 146
Lukas Graf Avatar answered Oct 13 '22 19:10

Lukas Graf


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' #.... 
like image 38
Jacob Krall Avatar answered Oct 13 '22 21:10

Jacob Krall