Circular iteration on tuple starting from a specific index

Ian Kelly ian.g.kelly at gmail.com
Thu Jun 1 12:13:13 EDT 2017


On Thu, Jun 1, 2017 at 4:14 AM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> guillaume.paulet at giome.fr wrote:
>>
>> def cycle_once(iterable, start):
>>     return chain(islice(iterable, start, None), islice(iterable, start))

This assumes that iterable is restartable, which is not the case if
iterable is itself an iterator.

> Another variation, maybe slightly more efficient:
>
> from itertools import islice, cycle
>
> def cycle_once(iterable, start):
>     return islice(cycle(iterable), start, start + len(iterable))

Similar problem here, len will fail on an iterator.

I know the OP specified a tuple (and that was what my own solution
assumed), but "iterable" implies broader applicability.



More information about the Python-list mailing list