iterators

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:

CharacteristicDescription
DefinitionAn iterator is an object that implements the iterator protocol, which consists of __iter__() and __next__() methods.
Iterator ProtocolConsists of two methods: __iter__() (returns the iterator object itself) and __next__() (returns the next item or raises StopIteration).
Iterable vs. IteratorAn iterable is an object that can return an iterator (e.g., lists, tuples, dictionaries). An iterator is an object that performs the iteration.
Creating IteratorsCustom iterators can be created by defining a class with __iter__() and __next__() methods.
Examplepython<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)
UsageUsed to iterate over sequences, custom collections, and other iterable data structures.
Memory EfficiencyIterators are memory efficient for large datasets as they generate items on-the-fly rather than storing them in memory.
Lazy EvaluationIterators use lazy evaluation, meaning they compute values on demand and do not store them.
Iteration ContextIterators are commonly used in for loops, comprehensions, and generator expressions.
Built-in IteratorsPython has many built-in iterators such as lists, tuples, strings, and ranges.
Infinite IteratorsIterators like those created by itertools.cycle can be infinite, continually providing values unless explicitly stopped.
Handling StopIterationThe StopIteration exception signals that iteration is complete and is handled automatically by for loops and comprehensions.
Custom Iterators vs GeneratorsCustom iterators require defining a class with __iter__() and __next__(), while generators provide a simpler way to create iterators using yield.
#reviewed #python #online #programming-language #algorithms #advanced #ready