user10019227
user10019227

Reputation: 117

Inexhaustible generator

I want to create a inexhaustible generator that always returns the number 4 using something from itertools. A sample output is below.

number = number_4()

next(number) == 4
    True
next(number) == 4
    True
next(number)
    4
next(number)
    4
next(number)
    4

Is there a reason this code wont work?

def number_4(): 
    """Return a generator that always returns the number 4"""
    itertools.repeat(4) = infinite
    return infinite

number = number_4()
print(next(number) == 4)
print(next(number))

Upvotes: 0

Views: 111

Answers (1)

wim
wim

Reputation: 362487

You are describing the basic usage of itertools.repeat.

>>> four = itertools.repeat(4)
>>> next(four)
4
>>> next(four)
4

Upvotes: 3

Related Questions