Some text some message..
Back 🔁 What is a Generator Object? 26 Jun, 2025

A generator object is a special type of iterator that generates values on the fly and doesn’t store them in memory like a list or tuple.

It is created:

  • When you use generator expressions:

    gen = (i*2 for i in range(5))
    
  • Or when you use a function with yield instead of return.


🔍 How It Works:

  • You get one value at a time using next() or a for loop.

  • It’s lazy, meaning it only computes values when needed.

  • It saves memory by not storing the whole collection.


✅ Example:

gen = (i * 2 for i in range(5))
print(gen)          # Output: <generator object ...>

print(next(gen))    # 0
print(next(gen))    # 2
print(next(gen))    # 4

You can also loop through it:

for num in gen:
    print(num)

🧠 Memory Comparison:

big_list = [i for i in range(1000000)]     # Takes a lot of memory
big_gen  = (i for i in range(1000000))     # Takes very little memory

⚠️ Important:

  • You can only loop through a generator once.

  • After that, it's exhausted:

gen = (i for i in range(3))
list(gen)  # [0, 1, 2]
list(gen)  # [] ← Empty because it's already used

📦 Summary Table

Feature Generator List
Memory Usage Low (lazy) High (stores all data)
Creation (i for i in x) [i for i in x]
Iterable multiple times ❌ No ✅ Yes
Speed Fast startup Faster access