Home > Blockchain >  How to do cycle loop in Python?
How to do cycle loop in Python?

Time:04-19

I have a problem doing cycle iteration in python list where if it reaches the maximum of the list then it will reverse to the beginning of the list and it will iterate again from the beginning. For example I have list of [3,4,5] then I want to loop this 6 times. So the iteration will be

3, 4, 5, 4, 3, 4, 5...

So how to do this loop?

CodePudding user response:

You can use itertools.cycle with some slicing:

from itertools import cycle, islice

lst = [3,4,5]
cycler = cycle(lst[:-1]   lst[:0:-1])
print(list(islice(cycler, 10))) # [3, 4, 5, 4, 3, 4, 5, 4, 3, 4]

CodePudding user response:

First construct a cycle-able version of your list by slicing it -- take the list forward and backward and remove the last element of each to keep them from being repeated:

>>> nums = [3, 4, 5]
>>> cycle = nums[:-1]   nums[:0:-1]

and then use the % operator to iterate an arbitrary number of times while keeping it within the range of your list:

>>> for i in range(6):
...     print(cycle[i % len(cycle)])
...
3
4
5
4
3
4
  • Related