Python Iterators
π Python Iterators β Full Tutorial
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().
