2

I created a simple generator:

def long_time():

    for i in range(10):

        yield i * 5  

a = long_time()

print(next(a))

print(next(a))

Here, I get the outputs 0 and 5, which is OK. But when I try to build the variable a as below:

def long_time():

    for i in range(10):
        yield i * 5
  
a = long_time

print(next(a()))

print(next(a()))

Both of the print outputs are 0. What is the difference, should I always call the generator with ()?

2 Answers 2

2

When you write

a = long_time 

you're just giving a different name to the function long_time.

So writing

print(next(a()))

is the same as writing

print(next(long_time()))

That is, in a single line, you get a generator object by calling long_time(), then pass it to next, getting the generator's first value 0. But since you don't have a reference to that generator, after that line you can't access the object anymore. On your next print... line, you're getting a fresh generator since it involves a new call to long_time().

This is fixed when a isn't a reference to the long_time function, but its return value (the generator) instead:

a = long_time()
Sign up to request clarification or add additional context in comments.

3 Comments

So even though, if I say a = long_time(), next(a) is still something else (return value) than next(long_time()). It is a bit confusing though...
The returned value is the same, the difference is whether you have a reference to it (i.e. store it in a variable) or not, so you can access it later on. It's like writing [1, 2, 3][0] versus mylist = [1, 2, 3]; mylist[0]: in both cases you get the first element of a list, but in the first example you don't have access to the list afterwards because you created it and extracted its first element in a single line. next_long_time()) is like the former, a = long_time(); next(a) is like the latter.
Thank you very much for the detailed description.
1

When you call long_time, you get back a fresh generator object. In your second example, a is just another name for the generator function, so each time you call a(), you get a new generator (just as if you had called long_time) that starts at 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.