iterator¶
- iterators are objects that allow you to iterate through a collection of elements one at a time.
- They provide a way to efficiently access elements in a sequence without loading the entire collection into memory at once.
- This is particularly useful for working with large datasets or when you only need to process elements one by one.
- Iterable vs. Iterator
- An iterable is an object that can be used to create an iterator.
- It defines a protocol for iterating, but it's not the iterator itself.
- Common iterables in Python include lists, tuples, strings, dictionaries (for keys), and sets.
- An iterator, on the other hand, is an object that implements the iterator protocol.
- It keeps track of the current position within the sequence and provides a way to access the next element.
- The Iterator Protocol
- An iterator must implement two special methods
__iter__(self)
: This method returns the iterator object itself. It's called when you use theiter()
function on an iterable.__next__(self)
: This method raises aStopIteration
exception when there are no more elements to iterate over. Otherwise, it returns the next element in the sequence.
- An iterator must implement two special methods
- You can obtain an iterator from an iterable using the built-in
iter()
function
In [ ]:
Copied!
numbers = [1, 2, 3, 4, 5]
number_iterator = iter(numbers)
numbers = [1, 2, 3, 4, 5]
number_iterator = iter(numbers)
- Using Iterators in
for
Loops- The for loop in Python automatically uses the iterator protocol behind the scenes.
- When you use a
for
loop with an iterable, Python internally creates an iterator object, calls__next__
repeatedly to get the next element, and assigns it to the loop variable untilStopIteration
is raised.
In [ ]:
Copied!
for number in numbers:
print(number) # This will print each number on a new line
for number in numbers:
print(number) # This will print each number on a new line
- Custom Iterators
- You can create your own custom iterators by defining a class that implements the iterator protocol (i.e., defines the
__iter__
and__next__
methods). - This allows you to create iterators for custom data structures or generate sequences on demand.
- You can create your own custom iterators by defining a class that implements the iterator protocol (i.e., defines the
- Benefits of Using Iterators
- Memory Efficiency: Iterators process elements one at a time, reducing memory usage compared to loading the entire collection at once. This is especially beneficial for large datasets.
- Lazy Evaluation: Some iterators, like those created with generator expressions, can be even more memory-efficient as they generate elements only when needed.
- Flexibility: Iterators provide a generic way to work with different data structures that support iteration.
- Common Use Cases
- Iterating over elements in lists, tuples, and strings.
- Processing elements in files line by line.
- Creating custom sequences using generator expressions or generator functions.