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
def generator_function(): yield value
Creating a Simple Generator for Barangay Leaders
# Generate a list of notable Filipino leaders one at a time def barangay_leaders(leaders): for leader in leaders: yield leader filipino_leaders = ["Jose Rizal", "Andres Bonifacio", "Emilio Aguinaldo", "Apolinario Mabini"] for leader in barangay_leaders(filipino_leaders): print(f"Barangay Leader: {leader}") """ Expected Output: Barangay Leader: Jose Rizal Barangay Leader: Andres Bonifacio Barangay Leader: Emilio Aguinaldo Barangay Leader: Apolinario Mabini """
Using zip with Generators for Festival Details
# Pair festivals with their dates and locations efficiently. def festival_details(festivals, dates, locations): for festival, date, location in zip(festivals, dates, locations): yield f"{festival} - {date} - {location}" festivals = ["Sinulog", "Ati-Atihan", "Pahiyas", "Panagbenga", "MassKara"] dates = ["January", "January", "May", "February", "October"] locations = ["Cebu City", "Kalibo", "Lucban", "Baguio", "Bacolod"] for detail in festival_details(festivals, dates, locations): print(detail) """ Expected Output: Sinulog - January - Cebu City Ati-Atihan - January - Kalibo Pahiyas - May - Lucban Panagbenga - February - Baguio MassKara - October - Bacolod """