Is there a way to return the next element in a list on a function call, this is what I have tried so far:
from itertools import cycle
def get_next_element():
lst = [1, 2, 3, 4]
cycle_list = cycle(lst)
return next(cycle_list)
Now when I call the above function:
while True:
x = get_next_element() # x should return 1, 2, 3
But x is always returned as 1 every time the function is called within the loop.
CodePudding user response:
You could subclass cycle
in order to make it callable.
from itertools import cycle
class mycycle(cycle):
def __call__(self):
return next(self)
Demo:
>>> get_next_element = mycycle([1, 2, 3])
>>> get_next_element()
1
>>> get_next_element()
2
>>> get_next_element()
3
>>> get_next_element()
1