Search code examples
pythonlistcycle

Python: cycle through elements in list reversing when the end is reached


I have a list that looks like:

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']

I need to cycle through this list one element at a time but when the end of the list is reached, the cycle needs to be reversed.

For example, using itertools.cycle:

from itertools import cycle
a_cycle = cycle(a)
for _ in range(30):
    print a_cycle.next()

I get:

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10

but what I need is:

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 10, 09, 08, 07, 06, 05, 04, 03, 02, 01, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10

I need to cycle through a for a fixed number of times, say 200.


Solution

  • You can cycle the chain of your a and reversed a, eg:

    from itertools import cycle, islice, chain
    
    a = range(1, 11)
    b = reversed(a)
    c = cycle(chain(a, b))
    d = list(islice(c, 100)) # `c` is infinite - hence the `islice` to stop at some point...
    

    Which gives you:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    

    Note: If a is an exhaustable iterator, you will need to make a copy of a first. But given your example, this will be fine.