![]() |
Iterators are a fundamental concept in Python, allowing you to traverse through all the elements in a collection, such as lists or tuples. While Python provides built-in iterators, there are times when you might need to create your own custom iterator to handle more complex data structures or operations. In this article, we will explore how to build a basic iterator in Python from scratch. What is an Iterator?An iterator in Python is an object that implements two methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself and is called once at the beginning of an iteration. The __next__() method returns the next value from the sequence and raises a StopIteration exception when there are no more items to return. Define the Iterator Class:
Why Use Custom Iterators?Custom iterators allow you to:
Example 1: Building a Basic Custom IteratorLet’s build a basic iterator that generates a sequence of square numbers. We’ll start by creating a class that implements the iterator protocol. Initialization: The SquareIterator class is initialized with a maximum value max_n, which determines how many squares will be generated. The current attribute keeps track of the current number being squared. Iteration: The __iter__ method is straightforward; it returns the iterator object itself (self). This method is necessary to make our object an iterator. Generating Values: The __next__ method is where the core logic resides. It checks if the current value has exceeded the maximum (max_n). If it has, it raises a StopIteration exception, which stops the iteration. Otherwise, it calculates the square of the current value, increments current, and returns the squared value.
Output: 0
1
4
9
16
25 Example 2: Building a Fibonacci IteratorWe’ll create an iterator that generates Fibonacci numbers up to a specified limit.
Output: Using for loop:
0
1
1
2
3
5
8
13
21
34
55
89
Using next() function:
0
1
1
2
3
5
8
13
21
34
55
89 ConclusionBuilding a custom iterator in Python is a powerful way to create more complex and memory-efficient data traversal mechanisms. By implementing the __iter__ and __next__ methods, you can control the iteration logic and manage state between iterations. The example provided here demonstrates how to create a simple iterator that generates square numbers, but the principles can be applied to more complex scenarios as well. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |