Python: looping through items in the reverse of a list when reaching the end

I have a list that looks like this:

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

      

I need to loop through this list one item at a time, but when the end of the list is reached, the loop 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 i need:

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 loop through a

for a fixed number of times, say 200.

+3


source to share


4 answers


You can yours and , for example:cycle

chain

a

reversed

a

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 exhaustive iterator, you need to make a copy first a

. But given your example, everything will be fine.

+10


source


Do you really need to loop through the list, like in the future, back and forth? Or just a .reverse()

list?

print a + a[::-1]

      

Will do what you describe. reversed()

also works, but you need chain()

it since it returns an iterator like:



print list(itertools.chain(a, reversed(a)))

      

You can call itertools.cycle()

on any result to get an infinite iterator of the list concatenated with its inverse.

+3


source


def forwardback(lst):
    tot = len(lst)
    while 1:
        for i in xrange(tot):
            yield lst[i]
        for i in xrange(tot-1,-1,-1):
            yield lst[i]

      

or (using an approach cycle

that works for all iterators)

def forwardback(lst):
    saved = []
    for elem in lst:
        yield elem
        saved.append(elem)
    while saved:
        for elem in reversed(saved):
            yield elem
        for elem in saved:
            yield elem

      

+2


source


Make a copy of list a, cancel it, then add it.

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
b = a[:]
b.reverse()
a = a + b

      

or based on a suggestion of a comment.

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
b = a[::-1]
a = a + b

      

+2


source







All Articles