Python Iterators
🐍 Python Iterators
An iterator is an object that allows you to iterate (loop) through a sequence of values—such as strings, lists, tuples, etc.
Iterators are used when you want to process items one at a time.
✅ What Makes an Object Iterable?
An object is iterable if:
-
It can return items one by one
-
It contains the method
__iter__()
Examples: list, tuple, string, set, dict
What is an Iterator?
An iterator is an object that implements:
| Method | Purpose |
|---|---|
__iter__() |
Returns the iterator object |
__next__() |
Returns the next value |
Example: Using Iterator Manually
If you call next() again, you get:
Using Iterators in Loops
Instead of writing next() manually, Python automatically uses iterators inside loops:
String as an Iterator
🧠 Creating Your Own Iterator Class
You can create a custom iterator by defining the two required methods:
Output:
Infinite Iterators
You can create infinite iterators (no stopping condition).
Use carefully to avoid infinite loops.
Iterator vs Iterable (Quick Difference)
| Feature | Iterable | Iterator |
|---|---|---|
| Can be looped | ✅ Yes | ✅ Yes |
Needs __iter__() |
✅ Yes | ✅ Yes |
Needs __next__() |
❌ No | ✅ Yes |
| Examples | list, tuple, str |
iter(list) |
Why Use Iterators?
✔ Saves memory (values created one at a time)
✔ Useful for large datasets
✔ Used in loops, generators, and file reading
🧠 Real Example: Reading Files with Iterator
Python reads one line at a time → efficient for large files.
📌 Summary
-
Iterators let you loop through values one at a time.
-
Any object with
__iter__()is iterable. -
Iterator object must also have
__next__(). -
Best used for large data and memory-efficient looping.
🚀 Practice Exercises
-
Create an iterator that prints numbers from
1 to 20. -
Make a countdown iterator starting from
10 to 1. -
Create an iterator that returns even numbers only.
-
Convert a string into an iterator and print characters using
next().
