0

I have searched for the answer to my question for hours but still can't find it.

from itertools import cycle

def repeat():
    i = [0, 1, 2]
    pool = cycle(i)
    print(next(pool))

repeat()

Every time I call the function, it gives 0.

I want the function to give 0, 1, 2, 0, 1, 2, 0, 1, 2, repeatedly every time it is called.

I know I can get what I want if I don't use it as a function. But I want to use it as a function.

Any help will be greatly appreciated! Thank you.

I got the idea of using itertools below: Circular list iterator in Python

layperson
  • 59
  • 4
  • Can you give a clear example of how you want to use this and why you "don't want to use it as a function"? I think the answer is going to depend on what you are trying to accomplish. – Craig May 22 '20 at 19:11

4 Answers4

1

Do you want something like this?

from functools import partial
from itertools import cycle

repeat = partial(lambda it: print(next(it)), cycle([0, 1, 2]))
repeat() # 0
repeat() # 1
repeat() # 2
repeat() # 0
repeat() # 1

Alternatively,

from itertools import cycle

def repeat(pool=cycle([0, 1, 2])):
    print(next(pool))
Aaron
  • 1,255
  • 1
  • 9
  • 12
1

Hacky, yet works:

def repeat():
    if not hasattr(repeat, 'pool'):
        repeat.pool = cycle([0,1,2])
    print(next(repeat.pool))
theEpsilon
  • 1,800
  • 17
  • 30
0

I get that you want repeat() to print/return the next element whenever it is called.

The reason this is not working is that every time the repeat() function is called, a local variable pool is created and the first element of that cycle is printed when next() is called on it.

The issue can be resolved by slightly modifying the above code so that the cycle is created outside of the repeat() function and the final code looks somewhat like this --

from itertools import cycle
i = [0, 1, 2]
pool = cycle(i)

def repeat():
    print(next(pool))

repeat()

space_mill
  • 359
  • 2
  • 5
0

What you are looking for is a generator( https://docs.python.org/3/tutorial/classes.html#generators) using the yield keyword.

from itertools import cycle

def repeat():
    i = [0, 1, 2]
    for j in cycle(i):
        yield(j)

i=0
for x in repeat():
    print(x)
    i += 1
    if i > 5 :
        break
Alan Hoover
  • 1,430
  • 2
  • 9
  • 13