Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In this tutorial, you'll learn about generators in Python. Generators are a type of iterator that allows you to create and iterate over a potentially infinite sequence of items using the yield
keyword. Generators are useful for producing items one at a time and processing large data sets, since they don't require you to store the entire sequence in memory.
A generator function is defined like a regular function, but instead of using the return
keyword, it uses the yield
keyword to produce items one at a time.
def count_up_to(max): count = 1 while count <= max: yield count count += 1 # Create a generator object counter = count_up_to(5) # Iterate over the generator for number in counter: print(number)
In this example, we have a generator function called count_up_to
that counts up to a specified maximum value. We create a generator object counter
and iterate over it using a for loop.
You can also use the next()
function to manually get the next item from a generator.
def count_up_to(max): count = 1 while count <= max: yield count count += 1 # Create a generator object counter = count_up_to(5) # Get the next item from the generator print(next(counter)) # Output: 1 print(next(counter)) # Output: 2 # Iterate over the remaining items for number in counter: print(number)
Generator expressions are a concise way to create generators using a syntax similar to list comprehensions, but with parentheses instead of square brackets.
# Create a generator expression squares = (x * x for x in range(1, 6)) # Iterate over the generator for square in squares: print(square)
In this example, we use a generator expression to create a generator that calculates the squares of the numbers from 1 to 5. We then iterate over the generator using a for loop.
You can chain multiple generators together to create more complex iterators.
def even_numbers(numbers): for number in numbers: if number % 2 == 0: yield number def squares(numbers): for number in numbers: yield number * number # Create a generator object numbers = range(1, 11) even_squares = squares(even_numbers(numbers)) # Iterate over the generator for even_square in even_squares: print(even_square)
In this example, we have two generator functions: even_numbers
, which yields even numbers from a given sequence, and squares
, which yields the squares of the numbers in a given sequence. We chain these generators together to create a generator that yields the squares of even numbers from 1 to 10.
Generators are a powerful and memory-efficient way to create iterators in Python, allowing you to produce and process large sequences of items one at a time without storing the entire sequence in memory.
How to create a generator in Python:
yield
keyword to create a generator function.def my_generator(): yield 1 yield 2 yield 3 gen = my_generator() for value in gen: print(value)
Python generator expressions:
gen_expr = (x ** 2 for x in range(5)) for value in gen_expr: print(value)
Infinite generators in Python:
def infinite_generator(): count = 0 while True: yield count count += 1 gen = infinite_generator() for _ in range(5): print(next(gen))
Passing values to generators in Python:
send()
method.def echo_generator(): while True: received = yield print("Received:", received) gen = echo_generator() next(gen) # Advance to the first yield gen.send("Hello")
Exception handling in Python generators:
try-except
blocks.def my_generator(): try: yield 1 yield 2 raise ValueError("Error in generator") except ValueError as e: print(f"Exception: {e}") gen = my_generator() next(gen) next(gen)