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

Python Generators

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.

  • Creating a generator function:

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.

  • Manually controlling a generator:

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:

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.

  • Chaining generators:

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.

  1. How to create a generator in Python:

    • Description: Use the yield keyword to create a generator function.
    • Code:
      def my_generator():
          yield 1
          yield 2
          yield 3
      
      gen = my_generator()
      for value in gen:
          print(value)
      
  2. Python generator expressions:

    • Description: Create concise generators using generator expressions.
    • Code:
      gen_expr = (x ** 2 for x in range(5))
      for value in gen_expr:
          print(value)
      
  3. Infinite generators in Python:

    • Description: Create generators that produce an infinite sequence of values.
    • Code:
      def infinite_generator():
          count = 0
          while True:
              yield count
              count += 1
      
      gen = infinite_generator()
      for _ in range(5):
          print(next(gen))
      
  4. Passing values to generators in Python:

    • Description: Send values into generators using the send() method.
    • Code:
      def echo_generator():
          while True:
              received = yield
              print("Received:", received)
      
      gen = echo_generator()
      next(gen)  # Advance to the first yield
      gen.send("Hello")
      
  5. Exception handling in Python generators:

    • Description: Handle exceptions within generators using try-except blocks.
    • Code:
      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)