Python Generators – Complete Beginner to Advanced Guide
A Generator in Python is a special type of function that allows you to create your own iterator. It returns values one-by-one using the yield keyword instead of returning all values at once.
Generators are extremely powerful when working with large data, streams, loops, or memory-sensitive applications.
What Is a Generator?
A generator is a function that behaves like an iterator. Instead of returning a single value and ending execution, a generator:
- Produces a sequence of values
- Pauses after each value using yield
- Resumes execution from the same point when
next()is called
In simple words: Generator = Function + Iterator + Yield
Why Use Generators?
- They save memory (lazy evaluation)
- They generate values on-demand
- Faster performance for large datasets
- Replaces complex iterator classes
- Easy to read and write
Difference Between yield and return
| yield | return |
|---|---|
| Pauses function execution | Ends function execution |
| Returns value without losing state | Returns final value and loses state |
| Used to create generators | Used to return a final result |
Basic Generator Example
def fun():
print(10)
yield
# return 1 # return stops execution permanently
print(20)
yield
# Calling generator
x = fun()
next(x)
next(x)
Explanation:
- The first
next(x)prints 10 and pauses atyield. - The second
next(x)resumes execution, prints 20, and pauses again.
Generator for Looping (Iterator Example)
def loop(x):
for i in range(x):
yield i
l = loop(5)
while True:
try:
print(next(l))
except StopIteration:
break
This generator behaves exactly like range(), generating values one by one.
Extra Generator Examples (Added for Better Learning)
1. Generator to Produce Even Numbers
def even_numbers(n):
for i in range(0, n+1, 2):
yield i
for num in even_numbers(10):
print(num)
2. Generator to Read Large Files Efficiently
def read_file_line_by_line(filename):
with open(filename, "r") as f:
for line in f:
yield line
for line in read_file_line_by_line("data.txt"):
print(line)
Use Case: You can read GB-size files without loading them fully into memory.
3. Infinite Generator (Useful for Streaming)
def infinite_counter():
num = 1
while True:
yield num
num += 1
counter = infinite_counter()
print(next(counter))
print(next(counter))
print(next(counter))
4. Generator Expression (Short Syntax)
squares = (x*x for x in range(5))
for n in squares:
print(n)
Similar to list comprehension but memory efficient.
When Should You Use Generators?
- Processing large datasets
- Streaming data applications
- Building custom iterators
- Reading big files line-by-line
- Creating pipelines (just like Unix)
YouTube Video (Reference)
Assignments for Practice
- Create a generator that produces Fibonacci series.
- Create a generator that yields prime numbers up to 100.
- Create a generator that yields characters of a string one by one.
- Create a generator for multiplication table of a number.
- Create an infinite generator for random OTP generation.
0 Comments
POST Answer of Questions and ASK to Doubt