Generators in Python
Learn how Python generators produce values one at a time
using the yield keyword.
What is a Generator?
A generator is a special type of function that produces values one at a time instead of creating and returning all values at once.
Generators use the yield keyword to return
a value and pause the function until the next value
is requested.
yield keyword.
Generator Flow
Generator Function
Function contains one or more yield statements.
yield
Produces one value and pauses execution.
Next Value
Function continues when another value is requested.
Basic Syntax
def generator_function():
yield value
A function containing yield becomes
a generator function.
Simple Generator Example
def numbers():
yield 10
yield 20
yield 30
for number in numbers():
print(number)
Output:
10
20
30
The generator produces each value one at a time.
Using yield
The yield keyword returns a value from
a generator and pauses its execution.
def show_numbers():
yield 1
yield 2
yield 3
generator = show_numbers()
print(next(generator))
print(next(generator))
print(next(generator))
Output:
1
2
3
Generator with next()
We can use next() to retrieve values
from a generator one at a time.
def colors():
yield "Red"
yield "Green"
yield "Blue"
generator = colors()
print(next(generator))
print(next(generator))
print(next(generator))
Output:
Red
Green
Blue
Generator with for Loop
A generator can be directly used with a
for loop.
def courses():
yield "Python"
yield ".NET"
yield "Java"
for course in courses():
print(course)
Output:
Python
.NET
Java
Generator for Numbers
def count_numbers():
for number in range(1, 6):
yield number
for number in count_numbers():
print(number)
Output:
1
2
3
4
5
Generator Expression
A generator expression provides a short way to create a generator.
numbers = (number * 2 for number in range(1, 6))
for number in numbers:
print(number)
Output:
2
4
6
8
10
Generator vs List
List
A list stores all values in memory.
numbers = [1, 2, 3, 4, 5]
Generator
A generator produces values when they are requested.
numbers = (x for x in range(1, 6))
Memory Efficiency
Generators are useful when working with large amounts of data because values can be generated one at a time.
def large_numbers():
number = 1
while number <= 1000000:
yield number
number += 1
for number in large_numbers():
if number == 5:
print(number)
break
The generator produces values as needed instead of creating all one million values at once.
Example 👀🌍
The following example generates student marks one at a time.
def student_marks():
yield 75
yield 82
yield 90
for marks in student_marks():
print("Marks:", marks)
Output:
Marks: 75
Marks: 82
Marks: 90
Advantages of Generators
Memory Efficient
Values are produced when required instead of storing all values.
Easy to Use
A simple yield statement can create a generator.
Large Data
Generators are useful when processing large collections or streams of data.
Best Practices
Use yield
Use yield when values should be produced one at a time.
Use for Loop
Use a for loop when processing all generated values.
Avoid Unnecessary Lists
Use generators when you do not need all values stored at once.
Common Mistakes
-
Confusing
yieldwithreturn. -
Calling
next()after the generator has no more values. - Converting a generator to a list unnecessarily.
- Forgetting that a generator is consumed as values are requested.
Practice Programs
- Create a generator that produces numbers from 1 to 10.
- Create a generator that produces even numbers.
- Create a generator for course names.
-
Use
next()to retrieve generator values. - Create a generator that produces student marks.
Summary
Generators are special functions that produce values
one at a time using the yield keyword.
They are memory efficient and useful for processing
large amounts of data. Generator values can be
accessed using next() or a
for loop.