The essence:
With a list like ['A', 'B', 'C']
, I'm trying to build or find a function that will return the next element of the list each time it's called. And if it, in this case, is called more than three times, then A
will be returned. And after that B
etc.
The details and what I've tried:
I've got a list of colors ['A', 'B', 'C']
that I'm applying to different objects. The number of objects may vary each time the code is run. If I've got more objects than colors in the list, I'd like the fourth object to have the color 'A'
. So, as the title says, I'd like to loop through a list by and index and start from the beginning if index > len(list)
. The following custom function looper
will do just that.
def looper(lst, runs):
j = 0
for i in range(0, (len(lst)+(runs-(len(lst))))):
if i < len(lst):
print(lst[i])
else:
print(lst[j])
j +=1
Test 1
# input:
runs = 2
looper(['A', 'B', 'C'], runs)
# output:
A
B
Test 2
#input :
runs = 5
looper(['A', 'B', 'C'], runs)
#output :
A
B
C
A
B
As you can see, this simple function will break if runs
gets large enough. And adding to that, every time this function is called, I would like to start at the index where the last call ended. So, moving on from the last example, the next time this is called:
runs = 1
looper(['A', 'B', 'C'], runs)
Then the output would be:
c
Having not yet quite wrapped my head around the use of generators, I can only guess that this would be a useful approach. But I've picked up that you should only use a generator if you'd like to loop through a list once as per the top answer in the post Generator Expressions vs. List Comprehension. So as far as I know, a generator would not be useful after all since Resetting a generator object in Python seems to be a bit complicated. Thank you for any suggestions!