In Python, iterators are an essential concept for working with sequences of data. They allow you to traverse through elements one at a time, making them particularly useful for loops and other operations.
What is an Iterator?
An iterator is an object in Python that implements the iterator protocol, which consists of two methods:
__iter__()
returns the iterator object itself.__next__()
returns the next value in the sequence. If there are no more items, it raises aStopIteration
exception.
An integrator is an object that can be iterated upon which means that you can traverse through all the values. Lists, tuples, dictionaries, and sets are all iterable objects.
What is an Iterable?
An iterable is an object that can return an iterator using the iter()
function. Common examples of iterables include lists, tuples, strings, dictionaries, and sets.
Example 1: Using a List as an Iterable
# define a list my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) # iterate through it using next() # Output: 4 print(next(my_iter)) # Output: 7 print(next(my_iter)) # next(obj) is same as obj.__next__()
Iterators in Loops
Python’s for
loop is designed to work with iterators. It automatically calls iter()
on the iterable and handles the StopIteration
exception for you.
Example 2: Iterating with a for
Loop
# Using a for loop to iterate over a list
for item in [1, 2, 3, 4]:
print(item)
Key Points
- Iterators allow you to process items one by one, which is memory-efficient for large data sets.
- Many built-in Python objects are iterables (e.g., lists, strings, dictionaries).
- Use the
iter()
function to create an iterator from an iterable. - Define
__iter__()
and__next__()
to create custom iterators.
When to Use Iterators?
- When working with streams of data (e.g., reading files line by line).
- When you need lazy evaluation, process one item at a time instead of loading all data into memory.
- When designing custom sequences or infinite data generators.
Why use iterators?
Iterators allow us to create and work with lazy iterable which means you can use an iterator for the lazy evaluation. This allows you to get the next element in the list without re-calculating all of the previous elements. Iterators can save us a lot of memory and CPU time.
Python has many built-in classes that are iterators, Example, enumerate, map, filter, zip and reversed, etc. Objects are iterators
Try this yourself: Implement an iterator for the Fibonacci sequence or any custom sequence to deepen your understanding!