Iterators
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Iterators
Definition: An iterator is an object in Python that contains a countable number of values and can be iterated upon, meaning you can traverse or step through all the values one by one. Technically, an iterator implements the iterator protocol, which consists of the methods __iter__() and __next__().
Why: Iterators work quietly behind the scenes of every for loop you write in Python. Understanding them helps you see how Python handles large sequences of data efficiently, retrieving elements one at a time only when requested, which saves system memory.
Iterable vs. Iterator
- Iterable: Anything you can loop over (like a List, Tuple, Set, Dictionary, or String). An iterable has data, but it is not the iterator itself; it is simply capable of producing one.
- Iterator: The actual object that manages the state and remembers its current position during a loop, fetching the next item when prompted.
Example
mytuple = ("a", "b", "c")
# 1. Get an iterator from the iterable tuple
myit = iter(mytuple)
# 2. Move through the sequence manually
print(next(myit)) # Output: a
print(next(myit)) # Output: b
print(next(myit)) # Output: c
Explanation
- The
iter()Function: This built-in function converts an iterable object (like our tuple) into a standard iterator object (myit). - The
next()Function: Each time you pass the iterator intonext(), it pulls the very next item out of the sequence. - The StopIteration Error: If you were to call
print(next(myit))a fourth time in this example, the program would raise aStopIterationerror because the sequence has run out of elements. Aforloop handles this error automatically behind the scenes to exit cleanly.
Key Notes
- Lists, tuples, dictionaries, and sets are all **iterable objects**. They are iterable containers which you can get an iterator from.
- Custom Iterators: You can turn any custom class into an iterator by defining
__iter__()(which returns the object itself) and__next__()(which defines how to fetch the next value and when to raiseStopIteration). - Iterators are **one-way streets**. Once you traverse through an iterator to the end, it is exhausted, and you cannot reset it or go backward; you must create a new iterator object to loop again.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute