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
.
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.
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)
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
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
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 |