__next__() Method Of Generator Iterators

Overview:

  • The __next__() function of the generator iterator starts/resumes a generator function.
  • The __next__() method resumes the current yield statment and returns the value of the next yield.
  • The __next__() method is used by the built-in function next() as well as the for loops.

Example:

# Example python program that uses __next__(), next 
# and for on a generator iterator object
def genyfunction():
    num = 0
    while num < 10:
        num = num + 2
        yield num 

# Create a generator iterator
geny           = genyfunction()

# Use the __next__() method 
receivedValue = geny.__next__() 
print("Received value using __next__():%d"%receivedValue)

# Get the value through the built-in function next() 
receivedValue = next(geny)
print("Received value using next():%d"%receivedValue)

# Now use a for loop
for val in geny:
    print("Received value using for:%d"%val)

# Try getting a value after the generator is exhaust
receivedValue = geny.__next__() 

Output:

Received value using __next__():2

Received value using next():4

Received value using for:6

Received value using for:8

Received value using for:10

Traceback (most recent call last):

  File "/Users/vinodh/pprogs/gennext1.py", line 25, in <module>

    receivedValue = geny.__next__() 

StopIteration


Copyright 2023 © pythontic.com