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


Groups > comp.lang.python > #20023

Re: Cycle around a sequence

Path csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!de-l.enfer-du-nord.net!feeder2.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail
From Neil Cerutti <neilc@norwich.edu>
Newsgroups comp.lang.python
Subject Re: Cycle around a sequence
Date 8 Feb 2012 14:25:33 GMT
Organization Norwich University
Lines 30
Message-ID <9pfeutFtjiU2@mid.individual.net> (permalink)
References <mailman.5525.1328663401.27778.python-list@python.org>
Mime-Version 1.0
Content-Type text/plain; charset=us-ascii
Content-Transfer-Encoding 7bit
X-Trace individual.net d9UrASszOKtbCqKmfz4ZaAvaElSA+mu5hqFTdtSoBFgLTHnQ+C
Cancel-Lock sha1:A36z79tq788ItAW+DTvgcthOCtk=
User-Agent slrn/0.9.9p1/mm/ao (Win32)
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:20023

Show key headers only | View raw


On 2012-02-08, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:
> I'm looking at a way of cycling around a sequence i.e. starting
> at some given location in the middle of a sequence and running
> to the end before coming back to the beginning and running to
> the start place.  About the best I could come up with is the
> following, any better ideas for some definition of better?

Python's indices were designed for these kinds of shenanigans.

def rotated(seq, n):
    """Iterate through all of seq, but starting from index n.

    >>> ", ".join(str(n) for n in rotated(range(5), 3))
    '3, 4, 0, 1, 2'
    """

    i = n - len(seq)
    while i < n:
        yield seq[i]
        i += 1

if __name__ == "__main__":
    import doctest
    doctest.testmod()

If you have merely an iterable instead of a sequence, then look
to some of the other clever stuff already posted.

-- 
Neil Cerutti

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