0Pricing
Learn AI with Python · Lesson

Generators

Understand generators and their use for creating iterators.

1

Introduction to Generators

Generators are a special type of iterator in Python that allow you to iterate over data lazily. Instead of returning all the data at once, they yield one item at a time, making them memory-efficient.

In this lesson, you’ll learn how to create and use generators in Python.

Generators — illustration 1

2

What Is a Generator?

A generator is a function that uses the yield keyword to return values one at a time. Each call to the generator’s next() method resumes execution from where it last yielded.

# Basic generator example
def my_generator():
    yield 1
    yield 2
    yield 3

# Using the generator
gen = my_generator()
print(next(gen))  # Outputs: 1
print(next(gen))  # Outputs: 2
print(next(gen))  # Outputs: 3

All lessons in this course

  1. Decorators
  2. Generators
  3. Context Managers (with Statements)
  4. Comprehensions (List, Set, and Dictionary)
  5. Iterators and Iterables
← Back to Learn AI with Python