It's my understanding that using a Generator is the best way to achieve something like this, but I'm open to suggestions.
Specifically, one use case is this: I'd like to print some items alongside another list, of an arbitrary length, truncating the initial iterator as necessary.
Here is working python code that demonstrates the exact example behavior I desire:
def loop_list(iterable): """ Return a Generator that will infinitely repeat the given iterable. >>> l = loop_list(['sam', 'max']) >>> for i in range(1, 11): ... print i, l.next() ... 1 sam 2 max 3 sam 4 max 5 sam 6 max 7 sam 8 max 9 sam 10 max >>> l = loop_list(['sam', 'max']) >>> for i in range(1, 2): ... print i, l.next() ... 1 sam """ iterable = tuple(iterable) l = len(iterable) num = 0 while num < l: yield iterable[num] num += 1 if num >= l: num = 0
As you may have noticed, this only works on lists/tuples/iterables that implement __getitem__
(if I'm not mistaken). Ideally, I'd like to be able to pass any iterable, and receive a generator that can properly loop over it's content.
If there's a better way to do something like this without a generator, I'm fine with that as well.
In Python, the functions itertools. count() , itertools. cycle() , and itertools. repeat() in the standard library itertools module can be used to create infinite iterators.
This is because generators, like all iterators, can be exhausted. Unless your generator is infinite, you can iterate through it one time only.
The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.
Iterator in Python is any python type that can be used with a ' for in loop '. Python lists, tuples, dictionaries, and sets are all examples of inbuilt iterators. But it is not necessary that an iterator object has to exhaust, sometimes it can be infinite. Such type of iterators are known as Infinite iterators.
You can use itertools.cycle
(source included on linked page).
import itertools a = [1, 2, 3] for element in itertools.cycle(a): print element # -> 1 2 3 1 2 3 1 2 3 1 2 3 ...
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