Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20048

Re: Cycle around a sequence

References <mailman.5525.1328663401.27778.python-list@python.org> <4f3343b2$0$1615$c3e8da3$76491128@news.astraweb.com>
Date 2012-02-09 15:16 +1100
Subject Re: Cycle around a sequence
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.5564.1328761006.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Feb 9, 2012 at 2:55 PM, Steven D'Aprano
<steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Cycle around a sequence Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-02-08 01:10 +0000
  Re: Cycle around a sequence Christoph Hansen <ch@radamanthys.de> - 2012-02-08 03:01 +0100
  Re: Cycle around a sequence Neil Cerutti <neilc@norwich.edu> - 2012-02-08 14:25 +0000
    Re: Cycle around a sequence Terry Reedy <tjreedy@udel.edu> - 2012-02-08 15:15 -0500
    Re: Cycle around a sequence Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-02-08 22:47 +0000
    Re: Cycle around a sequence Serhiy Storchaka <storchaka@gmail.com> - 2012-02-09 12:10 +0200
  Re: Cycle around a sequence Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-02-09 03:55 +0000
    Re: Cycle around a sequence Chris Angelico <rosuav@gmail.com> - 2012-02-09 15:16 +1100
    Re: Cycle around a sequence Peter Otten <__peter__@web.de> - 2012-02-09 09:33 +0100
    Re: Cycle around a sequence Chris Angelico <rosuav@gmail.com> - 2012-02-09 21:34 +1100

csiph-web