Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the next element of a list on a function call

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading