Home
About Us Privacy Policy
 

ITERATORS IN PYTHON

ADVERTISEMENT

Advanced Iterators



What are iterators, and why are they used?

In Python, an iterator is an object used to traverse over a pre-determined finite number of elements. Upon every iteration, the next value from the iterator object is fetched and utilized. But, before we begin delving into iterators, let us understand their usefulness and how they help develop programs.

Let us take an example of a Tenant Management System. Suppose you want to go through the entire list of tenants and look for their payment status. Most programming languages provide the for-loop and while-loop. Let us break down each component of these loops and how they operate on the data set.


For Loop

for <initializer>; ; Statement 1 Statement 2 Statement 3 ... ... ... Statement N


While Loop

<initializer>
while <initializer> <condition>:
    Statement 1
    Statement 2
    Statement 3
    ...
    ...
    ...
    Statement N
    <update>

In these loops, <initializer>, <condition> and <update> are optional. As a result, this might lead to hard-to-understand code, bugs. The programmer often forgets to put the <update> code, causing the program to get stuck.

Iterator, however, automatically handles all three steps: initialization, condition, and update. This abstraction gives the programmer the advantage of focusing on implementing the solution while developing accurate, maintainable, bug-free applications.


ADVERTISEMENT

In-Built Iterator Data Type Objects

Python provides several in-built iterator data types such as String, List, Tuples, and Dictionaries.

Let us go through every one of their examples.

Strings

hex_characters = "0123456789abcdefABCDEF"
for every_char in hex_characters:
    print(every_char)

0
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
A
B
C
D
E
F

Lists

fruits = ["apple", "orange", "cherry", "peach", "mango"]
for each_fruit in fruits:
    print(each_fruit)

apple
orange
cherry
peach
mango

Tuples

fruits = ("apple", "orange", "cherry", "peach", "mango")
for each_fruit in fruits:
    print(each_fruit)

apple
orange
cherry
peach
mango

Dictionary

personal_details = {
    "name": "James Bond",
    "age": 46,
    "address": "Unit 007, Street 07, Blakely Street, UK",
}

for detail in personal_details:
    print(personal_details[detail])

James Bond
46
Unit 007, Street 07, Blakely Street, UK


ADVERTISEMENT

Implementing Custom Iterator

We have gone through the in-built iterators and the advantage they have. It would be instrumental if we could implement a custom iterator to implement business-related solutions. The developers of Python have thought of this scenario and provided the capability to do such that.

To implement a custom iterator, we must implement the following methods, __iter__() and __next__() in the implementation class.

But before we learn to implement them, let us understand what each method does and what it returns.

__iter__(): This method can initialize the object, but it must always return the iterator object itself.

__next__(): This method allows the programmer to do operations but must always return the next item in the sequence.

To terminate the iteration, you must make use of the following statement: raise StopIteration.

Here is an example:

class EvenNumbers:
    def __init__(self, limit):    
        self.limit = limit

    def __iter__(self):
        self.a = 0 
        return self
    
    def __next__(self):    
        x = self.a
        if x > self.limit:
            raise StopIteration
        self.a += 2
        return x

even_numbers = iter(EvenNumbers(10))

for n in even_numbers:
    print(n)

0
2
4
6
8
10

Let us break down every statement in the above example.

class EvenNumbers:

This statement informs Python that we are going to be defining a class called EvenNumbers.

def __init__(self, limit):
    self.limit = limit

This method __init__() accepts limit as an argument and assigns an instance variable limit denoted by self.limit and assigns it the value of the argument limit.

def __iter__(self):
    self.a = 0
    return self

The method __iter__() creates an instance variable a denoted by self.a, and assigns it the initial value of 0. It then returns a reference to itself.

def __next__(self):
    x = self.a
    if x > self.limit: 
        raise StopIteration
    self.a += 2
    return x

The __next__() method assigns the value of instance variable a to a temporary variable x. Then it checks whether the current value of x is greater than the limit as set in the method __init__(). If the limit is reached or exceeded, it will raise the StopIteration exception to stop the iteration. The exception is handled automatically, and no separate exception handling mechanism is required. If no exception is raised, it increments the value of a by two and returns the value of x.


ADVERTISEMENT

Conclusion

In this chapter, we learned about iterators and their importance while developing bug-free programs, iterating over an iterator using looping structures such as for and while loop. Additionally, we learned about several in-built data types that allow iteration and implementing a custom iterator.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.