Hi Pythonistas
We have already discussed what is iterator and what is generator in previous post. Today we are going the learn what is the difference between them
Key Differences Between Iterator and Generator
Feature | Iterator | Generator |
---|---|---|
How it's created | Manually using a class with __iter__ and __next__ |
Using a function with yield or generator expression |
Syntax | Verbose, boilerplate | Clean and concise |
Memory Efficiency | May store full data in memory | Produces values lazily (one at a time) |
Use Case | Custom iteration logic | Lazy sequences, large data, streams |
Let us check the lazy evaluation of generator with a example
import tracemalloc
def using_iterator():
nums = iter([x for x in range(10**6)])
return sum(nums)
def using_generator():
nums = (i for i in range(10**6))
return sum(nums)
tracemalloc.start() # Start tracking memory
sum_ = using_iterator() # Run the function
# Get memory usage statistics
current, peak = tracemalloc.get_traced_memory()
print("using using iterator")
print(f"Current memory usage: {current / 1024**2:.10f} MB")
print(f"Peak memory usage: {peak / 1024**2:.4f} MB")
tracemalloc.stop() # Stop tracking
tracemalloc.start() # Start tracking memory
sum_ = using_generator() # Run the function
# Get memory usage statistics
current, peak = tracemalloc.get_traced_memory()
print("\nusing using generator")
print(f"Current memory usage: {current / 1024**2:.10f} MB")
print(f"Peak memory usage: {peak / 1024**2:.4f} MB")
tracemalloc.stop() # Stop tracking
Output
using using iterator
Current memory usage: 0.0000305176 MB
Peak memory usage: 34.7535 MB
using using generator
Current memory usage: 0.0000305176 MB
Peak memory usage: 0.0003 MB
We can see that current memory for the both function is same because they return same data but difference is the peak
memmory usage we can see that peak memory for iterator is 34.7535MB but for generator it only 0.0003MB.
When to Use What?
Scenario | Go With |
---|---|
You need to write a simple, lazy iterable | Generator |
You need full control over state & iteration logic | Iterator |
You want better memory usage | Generator |
Hope you have learned the difference between iterator and generator please share your valuable suggestions with afsal@parseltongue.co.in