Understanding Iteration and Generators
Iteration allows you to process items one at a time. Generators extend this idea by producing values only when they are requested, which can help reduce memory usage.
Iterating with enumerate()
The enumerate() function provides both an item's position and its value.
sales = [12000, 18000, 15000]
for index, amount in enumerate(sales, start=1):
print(f"Day {index}: ₹{amount}")
This is useful when displaying indexed records or identifying which observation is being processed.
Iterating with zip()
The zip() function combines corresponding elements from multiple iterables.
products = ["Laptop", "Tablet", "Phone"]
sales = [25, 40, 60]
for product, quantity in zip(products, sales):
print(product, quantity)
The loop pairs each product with its sales quantity. By default, zip() stops when the shortest iterable is exhausted, so ensure that your collections align when every record matters.
Creating a Generator
A generator uses yield to produce values one at a time instead of building the entire result in memory.
def generate_numbers(limit):
number = 1
while number <= limit:
yield number
number += 1
for value in generate_numbers(5):
print(value)
Generators are helpful when processing large sequences or reading data incrementally. However, data science libraries such as Pandas and NumPy often provide more suitable tools for working with large structured or numerical datasets.
Python for Data Science
Vishalini A








