Cycle around a sequence

Chris Angelico rosuav at gmail.com
Thu Feb 9 05:16:43 CET 2012


On Thu, Feb 9, 2012 at 2:55 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> If your data is humongous but only available lazily, buy more memory :)

Or if you have a huge iterable and only need a small index into it,
snag those first few entries into a list, then yield everything else,
then yield the saved ones:

def cycle(seq,n):
	seq=iter(seq)
	lst=[next(seq) for i in range(n)]
	try:
		while True: yield next(seq)
	except StopIteration:
		for i in lst: yield i

>>> list(cycle(range(10,20),2))
[12, 13, 14, 15, 16, 17, 18, 19, 10, 11]

Requires storage space relative to n, regardless of the length of the iterator.

ChrisA



More information about the Python-list mailing list