What are Python Generators?
Generators are special functions that allow you to iterate over large datasets efficiently by yielding one item at a time, conserving memory.
Why Use Generators?
- Memory Efficiency: Handle large datasets without consuming excessive memory.
- Lazy Evaluation: Generate values on-the-fly as needed.
- Simplified Code: Write cleaner loops and iteration logic.
How to Use Generators
Syntax of a Simple Generator
x
1
def generator_function():
2
yield value
3
Creating a Simple Generator for Barangay Leaders
1
19
1
# Generate a list of notable Filipino leaders one at a time
2
3
def barangay_leaders(leaders):
4
for leader in leaders:
5
yield leader
6
7
filipino_leaders = ["Jose Rizal", "Andres Bonifacio", "Emilio Aguinaldo", "Apolinario Mabini"]
8
9
for leader in barangay_leaders(filipino_leaders):
10
print(f"Barangay Leader: {leader}")
11
12
"""
13
Expected Output:
14
15
Barangay Leader: Jose Rizal
16
Barangay Leader: Andres Bonifacio
17
Barangay Leader: Emilio Aguinaldo
18
Barangay Leader: Apolinario Mabini
19
"""
Using zip with Generators for Festival Details
1
22
1
# Pair festivals with their dates and locations efficiently.
2
3
def festival_details(festivals, dates, locations):
4
for festival, date, location in zip(festivals, dates, locations):
5
yield f"{festival} - {date} - {location}"
6
7
festivals = ["Sinulog", "Ati-Atihan", "Pahiyas", "Panagbenga", "MassKara"]
8
dates = ["January", "January", "May", "February", "October"]
9
locations = ["Cebu City", "Kalibo", "Lucban", "Baguio", "Bacolod"]
10
11
for detail in festival_details(festivals, dates, locations):
12
print(detail)
13
14
"""
15
Expected Output:
16
17
Sinulog - January - Cebu City
18
Ati-Atihan - January - Kalibo
19
Pahiyas - May - Lucban
20
Panagbenga - February - Baguio
21
MassKara - October - Bacolod
22
"""