PYTHON

Generators in Python


Generators are a special class of functions that simplify the task of writing iterators. They allow you to declare a function that behaves like an iterator, i.e., it can be used in a for loop to iterate over a sequence of values.

 

Key Concepts of Generators

  1. Iterator Protocol: Generators automatically implement the iterator protocol, which consists of the __iter__() and __next__() methods.
  2. Yield Statement: Generators use the yield statement to return values one at a time, pausing their state between each call.
  3. Lazy Evaluation: Generators produce items only when they are needed, which can lead to improved performance and lower memory usage.

 

 

 

Implementing Generators in Python

 

Basic Generator

A generator function is defined like a normal function but uses the yield statement instead of return to yield values one at a time.

Example:

def simple_generator():
   yield 1
   yield 2
   yield 3
# Using the generator
gen = simple_generator()
print(next(gen))  # Output: 1
print(next(gen))  # Output: 2
print(next(gen))  # Output: 3
# print(next(gen))  # Raises StopIteration
 
 

 

Generator with Loop

Generators are often used with loops to yield a series of values.

Example:

def countdown(n):
   while n > 0:
       yield n
       n -= 1
# Using the generator
for number in countdown(5):
   print(number)
 

Output:

5
4
3
2
1
 

 

Generator Expressions

Generator expressions provide a concise way to create generators. They are similar to list comprehensions but use parentheses instead of square brackets.

Example:

# List comprehension
squares_list = [x * x for x in range(10)]
# Generator expression
squares_gen = (x * x for x in range(10))
# Using the generator
for square in squares_gen:
   print(square)
 

Output:

0
1
4
9
16
25
36
49
64
81
 

 

 

Benefits of Using Generators

 

  • Memory Efficiency: Generators are memory efficient because they generate items one at a time and only when required.
  • Simplified Code: Writing a generator is simpler than writing an iterator class with __iter__() and __next__() methods.
  • Infinite Sequences: Generators can represent infinite sequences, such as streams of data or infinite mathematical series.

 


PYTHON