Search code examples
python-3.xrepeatpython-itertools

Why repeat function didn't work?


I'm new to Python. Can anyone explain why the repeat function doesn't do anything here?

from itertools import repeat

def f():
    print([5,8,9])

repeat(f(),3)

Solution

  • repeat is a generator function. When you call it, the function does not start executing. Instead, a generator object is initialized and returned.

    To obtain the items, you need to iterate over the generator object:

    for x in repeat(f(), 3):
        print(x)
    

    Or:

    items = list(repeat(f(), 3))