Using generator to cycle through numbers in a list

625 Views Asked by At

I am looking for a way to cycle through numbers in a list every time the function is called on it.

I have used a generator, and it returns the members of list one at a time, but I have not found a way to go back to the beginning of the list after function returns the last element.

def returnSeq(self, numRows):
    for seq in [0, 1, 2, 3, 2, 1]:
        yield seq

If there is a better way to achieve this, I would appreciate it.

Thank you in advance,

2

There are 2 best solutions below

1
On BEST ANSWER

Use a while loop:

def returnSeq(self, numRows):
    i = 0
    items = [0, 1, 2, 3, 2, 1]
    n_items = len(items)
    while True:
        yield items[i]
        i = (i + 1) % n_items

This keeps increasing i modulo the number of elements in the list. This means it's an infinite generator yielding the elements in the list repeatedly.

0
On

You're basically reimplementing itertools.cycle:

import itertools

itertools.cycle([0, 1, 2, 3, 2, 1]) # <- there's your infinite generator