Contents
Roadmap info from roadmap website
Iterators
An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods iter() and next() .
Visit the following resources to learn more:
Characteristic | Description |
---|---|
Definition | An iterator is an object that implements the iterator protocol, which consists of __iter__() and __next__() methods. |
Iterator Protocol | Consists of two methods: __iter__() (returns the iterator object itself) and __next__() (returns the next item or raises StopIteration ). |
Iterable vs. Iterator | An iterable is an object that can return an iterator (e.g., lists, tuples, dictionaries). An iterator is an object that performs the iteration. |
Creating Iterators | Custom iterators can be created by defining a class with __iter__() and __next__() methods. |
Example | python<br>class MyIterator:<br> def __init__(self, limit):<br> self.limit = limit<br> self.current = 0<br> def __iter__(self):<br> return self<br> def __next__(self):<br> if self.current < self.limit:<br> self.current += 1<br> return self.current - 1<br> else:<br> raise StopIteration<br><br>it = MyIterator(3)<br>for value in it:<br> print(value) |
Usage | Used to iterate over sequences, custom collections, and other iterable data structures. |
Memory Efficiency | Iterators are memory efficient for large datasets as they generate items on-the-fly rather than storing them in memory. |
Lazy Evaluation | Iterators use lazy evaluation, meaning they compute values on demand and do not store them. |
Iteration Context | Iterators are commonly used in for loops, comprehensions, and generator expressions. |
Built-in Iterators | Python has many built-in iterators such as lists, tuples, strings, and ranges. |
Infinite Iterators | Iterators like those created by itertools.cycle can be infinite, continually providing values unless explicitly stopped. |
Handling StopIteration | The StopIteration exception signals that iteration is complete and is handled automatically by for loops and comprehensions. |
Custom Iterators vs Generators | Custom iterators require defining a class with __iter__() and __next__() , while generators provide a simpler way to create iterators using yield . |