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.
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.