Iterators and Generators
-
Explore iterators and generators in Python to create efficient and scalable looping mechanisms.
Why We Use Iterators & Generators
Iterators and generators are used to process data step-by-step instead of loading everything into memory at once.
Main Reasons
Save Memory – values are generated one by one
Better Performance – faster for large data
Handle Large Files – no memory overflow
Clean & Simple Code – less lines of code
Used in Real Applications – files, streams, logs, data pipelines
Real-Life Examples
iter() – Convert Collection into Iterator
What is iter()?
iter() converts a collection (list, tuple, string) into an iterator.
Using iter()
This example converts a list into an iterator.
numbers = [10, 20, 30]
it = iter(numbers)
next() – Get Next Value
What is next()?
next() returns the next value from an iterator.
Using next()
This example fetches elements one by one from the iterator.
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Real-Life Example (Iterator)
Reading attendance list one student at a time
students = ["Amit", "Riya", "Neha"]
it = iter(students)
print(next(it))
print(next(it))
yield – Create Generator
What is yield?
yield returns a value
Pauses the function
Resumes from same point
➡ Used to create generators
Real-Life Example (Generator)
ATM gives cash note by note, not all at once
Simple Generator Using yield
This generator returns numbers one by one.
def my_generator():
yield 1
yield 2
yield 3
g = my_generator()
print(next(g))
print(next(g))
print(next(g))
Generator for Student Roll Numbers
This generator gives roll numbers one at a time.
def roll_numbers(n):
for i in range(1, n + 1):
yield i
for roll in roll_numbers(5):
print("Roll No:", roll)
Iterator vs Generator