Introduction
Ever cooked instant noodles? You only prepare what you need, no waste, no extra cooking. That’s exactly how Generators work in Python! Instead of creating everything at once, they generate data on demand.
What is a Generator?
A generator is like a function that remembers where it left off. Instead of returning everything at once, it yields values one at a time.
Normal Function vs Generator
Regular function (boring):
def get_numbers():
return [1, 2, 3, 4, 5]
Generator (smart & lazy):
def get_numbers():
for i in range(1, 6):
yield i
With return
, the function stops completely.
With yield
, the function pauses & resumes later.
Why Use Generators?
Saves Memory - No need to store everything in RAM! Faster Execution - Only generates data when needed! Infinite Sequences - Works for endless loops!
Example: Generating Fibonacci numbers infinitely!
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for _ in range(10):
print(next(fib), end=" ")
No giant list, just lazy calculations!
Generator vs List Comprehension
Feature | Generator | List Comprehension |
---|---|---|
Memory Usage | Small | Large |
Speed | Faster | Slower |
Data Handling | One at a time | All at once |
Use Case | Large/Infinite Data | Small Data |
Example:
squares_gen = (x ** 2 for x in range(10**6)) # Generator
squares_list = [x ** 2 for x in range(10**6)] # List (uses lots of memory!)
Generator is the winner for huge data!
Fun Challenge
Try making a generator that yields even numbers up to infinity!
def even_numbers():
num = 0
while True:
yield num
num += 2
# Testing
evens = even_numbers()
for _ in range(5):
print(next(evens), end=" ") # Output: 0 2 4 6 8
Now you’re a generator master!
Summary
Generators are memory-efficient & fast. Use yield
instead of return
. Perfect for large data or infinite loops. Less RAM, more speed = Win-Win!
Now go forth and generate Python greatness!
0 Comments