Iterators in Python



Python, a flexible and strong programming language, provides a wide range of tools and techniques to make manipulating and navigating through data easier. One such fundamental concept is iterators. Iterators provide an elegant and efficient way to iterate over elements in a sequence-like manner.

 

What are Iterators?

An iterator in Python is an object that enables sequential access to elements within an iterable (any object capable of returning its elements one at a time).

Iterator protocol follows two methods :

  •  __iter__()
  • __next__()

 

__iter__() method returns the iterator object itself, while __next__() returns the next element in the sequence. If there are no more elements, it raises the ‘StopIteration exception’.

 

Types of Iterators

  • Built In Iterators
  • User Defined Iterators

 

Built-In Iterators

Python provides built-in iterators for many data types, making it even more convenient to work with data. Some common examples include range(), enumerate(), zip(), and iter().

 

# Using built-in iterators

for i in range(1, 6):

    print(i)



for index, value in enumerate(['a', 'b', 'c']):

    print(index, value)



list1 = [1, 2, 3]

list2 = ['a', 'b', 'c']

for x, y in zip(list1, list2):

    print(x, y)

Output

1
2
3
4
5

0 a
1 b
2 c

1 a
2 b
3 c

 

User Defined Iterators

To create an iterator, you can define a class that implements the iterator protocol.

 

class ListIterator:

    def __init__(self, lst):

        self.lst = lst

        self.index = 0



    def __iter__(self):

        return self



    def __next__(self):

        if self.index >= len(self.lst):

            raise StopIteration

        value = self.lst[self.index]

        self.index += 1

        return value



# Usage:

my_list = [1, 2, 3, 4, 5]

my_iterator = ListIterator(my_list)

for item in my_iterator:

    print(item)

Output

1
2
3
4
5

 

The ListIterator class defines the __iter__() and __next__() methods.

The __iter__() method simply returns the iterator object itself, and __next__() retrieves the next element from the list until it reaches the end.

 

Advantages of Iterators 

 

Memory Efficiency: Iterators enable lazy evaluation, meaning elements are generated on the fly and consumed one at a time. This approach conserves memory, particularly when working with large or infinite data sets.

 

Performance: Iterators can enhance performance by avoiding unnecessary computation until an element is actually required. This is known as lazy evaluation, allowing for more efficient resource utilization.

 

Compatibility: Since iterators follow a standardized protocol, they can be used interchangeably with various Python constructs that accept iterables, such as loops, list comprehensions, and generator expressions.

 

Customization: By creating custom iterators, you can define your own logic for traversing and accessing elements from complex data structures, opening up possibilities for tailored data manipulation.



Thanks for feedback.



Read More....
Arrays and Lists in Python
Lambda or Anonymous Functions in Python
Most common built-in methods in Python
Python Decorators
Python Dictionaries