CodingNic

Intermediate Python

Generators

Intermediate Python 32 min read

Generators

Generators

In the last lesson, you learned about iterators.

Generators are a simple way to create iterators.

They are powerful, memory-friendly, and common in real Python projects.

What Is a Generator?

A generator is a function that returns values one at a time using yield.

Unlike return, it pauses after each value and continues later.

Why Generators Matter

Generators help you:

  • work with large data
  • save memory
  • create lazy sequences
  • stream values step by step

return vs yield

Using return

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

print(numbers())

Output

text
[1, 2, 3]

This creates all values at once.

Using yield

python
def numbers():
    yield 1
    yield 2
    yield 3

print(numbers())

Output

text
<generator object numbers at ...>

Get Values from Generator

Use a loop.

python
def numbers():
    yield 1
    yield 2
    yield 3

for num in numbers():
    print(num)

Output

text
1
2
3

Use next()

python
def colors():
    yield "Red"
    yield "Blue"

g = colors()

print(next(g))
print(next(g))

Output

text
Red
Blue

Generator with Loop

python
def count_up():
    for n in range(1, 4):
        yield n

for value in count_up():
    print(value)

Output

text
1
2
3

Why Memory Efficient?

A generator creates one value when needed.

It does not store the full result list first.

Example: Large Range

python
for num in range(1_000_000):
    pass

Generators are useful for large data like this.

Code Along

Create a generator named letters() that yields:

  • A
  • B
  • C

Loop and print each letter.

Mini Challenge

Create a generator named even_numbers().

Tasks:

  • Yield:

    • 2
    • 4
    • 6

Print all values.

Expected output:

text
2
4
6

Real World Use Case

Generators are used in file reading, APIs, streaming data, pipelines, and large reports.

Quiz

  1. What keyword creates generator values?
  2. What is the difference between return and yield?
  3. Why are generators memory-friendly?
  4. Can generators be used in loops?

Assignment

Create a generator that yields three city names and print them in a loop.

Summary

You learned how generators use yield to return values one at a time efficiently.