Python iterator is an object that “implements the iterator protocol, which consists of the methods __iter__() and __next__()”.
Iterators loop over a collection of items, such as lists, tuples, dictionaries, or sets, one element at a time. They allow you to traverse a collection in a memory-efficient way because they do not load all elements into memory at once but rather generate each element on-the-fly when you request it.
You can create an iterator object from an iterable (e.g., lists, tuples, dictionaries, sets, or strings) using the built-in “iter()” function.
To get the next item from the iterator, you use the built-in “next()” function.
When there are no more items left to return, the iterator raises a StopIteration exception.
main_list = [1, 2, 3, 4] # Create an iterator object from the list main_iterator = iter(main_list) # Iterate over the elements using the iterator print(next(main_iterator)) print(next(main_iterator)) print(next(main_iterator)) print(next(main_iterator)) # Raises StopIteration exception print(next(main_iterator))
1 2 3 4 Traceback (most recent call last): File "/Users/krunallathiya/Desktop/Code/pythonenv/env/app.py", line 13, in <module> print(next(main_iterator)) StopIteration
You can also loop over an iterable using a for loop, which automatically creates and handles the iterator for you:
main_list = [1, 2, 3, 4] # The for loop automatically creates and uses an iterator to loop over for item in main_list: print(item)
1 2 3 4
To create your own custom iterator, you can define a class that implements the __iter__() and __next__() methods:
class MyRange: def __init__(self, start, end): self.start = start self.end = end def __iter__(self): return self def __next__(self): if self.start >= self.end: raise StopIteration else: current = self.start self.start += 1 return current # Create a custom iterator that generates numbers from 1 to 4 main_range = MyRange(1, 5) # Iterate over the numbers using a for loop for number in main_range: print(number)
1 2 3 4
This example demonstrates creating a custom iterator that generates numbers in a specified range.
1 thought on “Python Iterators”
Thanks for the post