Notes
Introduction
Iterators are an important concept in Python programming that allow traversal through
elements of a collection such as lists, tuples, or sets. They provide a systematic way to
access elements one at a time without exposing the underlying structure.
In Python, iteration is commonly used in loops such as for loops. Behind the scenes, Python
uses iterators to fetch elements one by one from a collection.
Understanding iterators helps programmers write efficient code and better understand how
loops and data structures work internally.
Definition
An iterator in Python is an object that allows sequential access to elements of a collection
without exposing its internal representation.
An object is considered an iterator if it implements two methods: __iter__() and __next__().
The __iter__() method returns the iterator object itself, while the __next__() method returns
the next element in the sequence.
Iterable vs Iterator
An iterable is any object that can be iterated over, such as lists, tuples, strings, or
dictionaries.
An iterator is an object that actually performs the iteration.
For example, a list is an iterable, but when we use iter() on it, it becomes an iterator.
This distinction helps programmers understand how Python processes loops.
Working of Iterators
When a for loop is used, Python automatically creates an iterator from the iterable.
The loop repeatedly calls the __next__() method until all elements are accessed.
When there are no more elements, a StopIteration exception is raised.