Circular iteration on tuple starting from a specific index

Beppe giuseppecostanzi at gmail.com
Tue May 30 12:51:29 EDT 2017


Il giorno martedì 30 maggio 2017 18:43:42 UTC+2, Ian ha scritto:
> On Tue, May 30, 2017 at 10:25 AM, Beppe <giuseppecostanzi at gmail.com> wrote:
> > hi all
> >
> > I've a tuple, something like
> >
> > x = ("A","B","C","D","E","F","G","H",)
> >
> > I would want to iterate on all tuple's elements
> > starting from a specific index
> >
> >
> > something like
> >
> > Python 2.7.9 (default, Jun 29 2016, 13:08:31)
> > [GCC 4.9.2] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> x = ("A","B","C","D","E","F","G","H",)
> >>>> for i in x[2:]:
> > ...     print i
> > ...
> > C
> > D
> > E
> > F
> > G
> > H
> >>>>
> >
> >
> >
> > with the difference that I would want to restart from the beginning when I reach the end of the tupla
> >
> >
> > C
> > D
> > E
> > F
> > G
> > H
> > A
> > B
> >
> > I would want to make a circular iteration....
> >
> > suggestions?
> 
> for i in (x[2:] + x[:2]):
>     print(i)
> 
> Or using the itertools module you could chain islices together but
> that's more verbose and probably overkill as long as the tuples are
> small.

great....

in fact

print x[2:]
print x[:2]
print x[2:] + x[:2]

return
('C', 'D', 'E', 'F', 'G', 'H')
('A', 'B')
('C', 'D', 'E', 'F', 'G', 'H', 'A', 'B')

thank you Ian






More information about the Python-list mailing list