StopIteration error when calling next() on a Python generator multiple times
12:55 07 Mar 2026
import time
import numpy as np

def sensor_data_generator(n):
    for _ in range(n):
        reading = {
            "timestamp" : time.time(),
            "temperature" : np.random.uniform(20.0, 25.0),
            "humidity" : np.random.uniform(60.0, 100.0),
            "light" : np.random.uniform(0.0, 100.0)
        }
        yield reading
        time.sleep(1)

sensor_stream = sensor_data_generator(5)

for _ in range(6):
    print(next(sensor_stream))

I expected this to print 5 readings and handle the loop.

but output i got is 'It prints the first 5 readings, then raises error'

Stopiteration error

I tried this

gen = sensor_data_generator(5)

for reading in gen:
    print(reading)

this printed for 5 times and stopped

output

my questions :

  1. Why does this StopIteration occur?
  2. How can I handle it so the loop does not crash when calling next() more times than the generator length?
python generator stopiteration