0

I try to understand generator in python 3. I try the following code:

def int_gen():
    """Infinite integer generator"""
    n = 1
    while True:
        n = n + 1
        yield n

print(next(int_gen())) # 2 
print(next(int_gen())) # 2
print(next(int_gen())) # 2

However, in this case:

for i in int_gen():
    print(i)

The results as I expected:

2
3
4
...

Refering to: next, this answer and this example

Why do 2 results difference ?

Community
  • 1
  • 1
kha
  • 349
  • 3
  • 18

1 Answers1

2

Each time you call int_gen(), you make a new generator that restarts everything. If you want the generator to continue where it left off, you'll have to save it so you have something useful to pass to next().

it = int_gen()
print(next(it)) # 2
print(next(it)) # 3
print(next(it)) # 4
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97