Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!news-out2.kabelfoon.nl!newsfeed.kabelfoon.nl!xindi.nntp.kabelfoon.nl!feed.xsnews.nl!border-1.ams.xsnews.nl!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.057 X-Spam-Evidence: '*H*': 0.89; '*S*': 0.00; 'def': 0.13; '16,': 0.15; 'entries': 0.15; 'from:addr:rosuav': 0.16; 'from:name:chris angelico': 0.16; 'iterator.': 0.16; 'wrote:': 0.18; '>>>': 0.18; 'memory': 0.21; 'received:209.85.210.174': 0.21; 'received:mail- iy0-f174.google.com': 0.21; 'header:In-Reply-To:1': 0.22; 'feb': 0.22; 'index': 0.24; 'message-id:@mail.gmail.com': 0.29; 'yield': 0.29; 'pm,': 0.29; 'regardless': 0.31; 'thu,': 0.32; 'steven': 0.34; '17,': 0.34; 'try:': 0.34; 'to:addr:python-list': 0.35; 'list,': 0.36; 'else,': 0.37; 'but': 0.37; 'received:google.com': 0.37; 'received:209.85': 0.38; 'data': 0.38; 'except': 0.39; 'received:209': 0.39; 'to:addr:python.org': 0.40; 'huge': 0.61; 'more': 0.61; 'your': 0.61; 'buy': 0.68; '19,': 0.68; 'storage': 0.70 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=mime-version:in-reply-to:references:date:message-id:subject:from:to :content-type; bh=dV+I9eATLgHLjDiAHFVNUTxMoYUM++0HNFhP0MLZua8=; b=YS7og89UO8jmoqOtIhE6xuHeSkdC11vfskM8k3eGl8FT9jayDYrWy+XCrrLR9cYHZ1 Drc74ULD6bhk1Slp/b6MTTHUFbHzP7oAvSVCTavD/GEYu9qINyArUZA81gU1zLMehNQD tkPqOWFfIjfKLYivN2ozew04LFDc5XBZe8AnE= MIME-Version: 1.0 In-Reply-To: <4f3343b2$0$1615$c3e8da3$76491128@news.astraweb.com> References: <4f3343b2$0$1615$c3e8da3$76491128@news.astraweb.com> Date: Thu, 9 Feb 2012 15:16:43 +1100 Subject: Re: Cycle around a sequence From: Chris Angelico To: python-list@python.org Content-Type: text/plain; charset=ISO-8859-1 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 22 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1328761006 news.xs4all.nl 6938 [2001:888:2000:d::a6]:34707 X-Complaints-To: abuse@xs4all.nl Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:20048 On Thu, Feb 9, 2012 at 2:55 PM, Steven D'Aprano 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