Python Complete Lecture: Iterators in Python
A) Title:
Mastering Iterators in Python
B) Learning Objectives:
By the end of this lecture, students will be able to:
Understand the concept of iterators.
Differentiate between iterable and iterator objects.
Use built-in iterator functions like iter() and next().
Create custom iterators using classes.
C) Real-Life Motivation:
“Imagine going through a playlist song by song. You don’t play all at once —
you fetch one at a time. Iterators work similarly by providing the next value
on request.”
✔ Modern Tech Examples:
Data Processing: Streaming data from files.
Machine Learning: Batch data loading using iterators.
Web Scraping: Page-by-page navigation.
D) Theoretical Explanation:
1. What is an Iterator?
An object that allows traversing through all elements of a collection
(like lists, tuples, etc.) one element at a time.
Implements two methods: __iter__() and __next__().
Basic Example:
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
2. Iterable vs Iterator:
Iterable Iterator
Can be looped over (list, tuple, etc.) Object with __next__()
Uses iter() to get iterator Returns next item using next()
3. Creating a Custom Iterator:
class Counter:
def __init__(self, low, high):
[Link] = low
[Link] = high
def __iter__(self):
return self
def __next__(self):
if [Link] > [Link]:
raise StopIteration
else:
[Link] += 1
return [Link] - 1
for num in Counter(1, 3):
print(num)
E) Common Student Questions:
1. What is the difference between iterable and iterator?
2. How to manually iterate through a list?
3. What happens when StopIteration is raised?
F) Practice Tasks:
✔️Task 1: Create a list and manually iterate using iter() and next().
✔️Task 2: Write a custom iterator that prints numbers from 10 to 15.
✔️Task 3: Handle StopIteration gracefully.
G) Summary:
Iterator retrieves elements one at a time.
Iterable uses iter() to get an iterator.
Custom iterators are created using classes with __iter__() and
__next__().
H) Quiz (3 Questions):
1. What function returns an iterator object from an iterable?
2. What method must be defined in a custom iterator class?
3. What exception signals the end of iteration?
I) Homework:
✔️Write a class that iterates over vowels in a word.
✔️Create an iterator that prints square numbers up to 5 terms.
J) Viva/Interview Preparation:
✔️Difference between iterable and iterator?
✔️When does StopIteration occur?
✔️How to create your own iterator?
K) Real World Example (Bonus):
✔️File Reading: file_object = open('[Link]') — uses iterator for line-
by-line reading.
✔️Batch Processing in ML: Load batches using iterators.
✔️Web Scraping: Navigate paginated content.
Final Note:
“Iterators simplify data handling by fetching one item at a time — efficient
and Pythonic!”
Prepared By:
Anesh Meghwar IMCS University of Sindh