Generators in Python

Generators in Python

A Generator is a function that returns an iterator and generates values one by one using the yield keyword.

Unlike normal functions (which use return), generators:

  • Produce values lazily

  • Save memory

  • Handle large data efficiently

Normal Function vs Generator

Normal Function

def numbers():
return [1, 2, 3, 4, 5]

This stores all numbers in memory.

Generator Function

def numbers():
for i in range(1, 6):
yield i

This generates one value at a time.

How to Use a Generator

gen = numbers()

print(next(gen))
print(next(gen))

Or:

for num in numbers():
print(num)

Why Generators Are Powerful?

Imagine reading a large file (1GB file).

Using a normal list → High memory usage 
Using generator → Low memory usage 


Real Example: Reading a Large File

def read_file(filename):
with open(filename) as file:
for line in file:
yield line

This reads file line by line without loading entire file into memory.

Generator Expressions

Similar to list comprehension, but use () instead of [].

squares = (x*x for x in range(5))

for num in squares:
print(num)

This is memory efficient.

Decorators vs Generators (Quick Difference)

FeatureDecorators            Generators
Purpose            Modify function behavior                Generate values lazily
Keyword Used            @                yield
Memory Efficient            No                Yes
Used For            Logging, authentication                Large data processing

When Should You Use Them?

Use Decorators when:

  • You want reusable functionality

  • You don’t want to rewrite code

  • You need logging or authentication

Use Generators when:

  • Working with large data

  • Reading files

  • Processing streams

  • Building pipelines



Comments