Best practice to make a generator loop through a container infinite times

1845 views python

I'm trying to use a generator to return elements from a container, but it needs to return/exhaust all elements then do it again.

The reason I say this is if there's a faster/better or more pythonic way to do this than just a for loop as I don't need them in order but I don't want to get the same item twice until it has exhausted all elements.

The example below is a tuple, although if there is a better container type for this than I'm all ears.

elements = ('a', 'b', 'c', ...)

def get_next_element():
    while True:
        for e in elements:
            yield e

There's got to be a different way to do this, or is this the best way?

I'm using Python 3.6.

answered question

Yes, I must be having a stroke. Why didn't I look through itertools... facepalm Well maybe the way I asked helps someone else

1 Answer


Use the itertools.cycle() callable, which does just that:

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.

This does exactly what your pure-python function does, plus it caches elements so the input can be any iterator (not just an iterable such as a tuple), but does this in efficient C.

posted this

Have an answer?


Please login first before posting an answer.