Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Creating and Using Iterators in Python


In Python, an iterator is an object that allows you to traverse through all the elements in a collection (such as a list, tuple, or dictionary) one by one. This article will explain how to create and use iterators in Python, along with some examples to help you understand their functionality.

What is an Iterator?

An iterator is an object that implements two methods:

Creating an Iterator

To create an iterator, you need to define a class that implements both the __iter__() and __next__() methods. This class can then be used to iterate through a collection of data.

Example 1: Creating a Custom Iterator

    class MyIterator:
        def __init__(self, start, end):
            self.current = start
            self.end = end

        def __iter__(self):
            return self

        def __next__(self):
            if self.current <= self.end:
                self.current += 1
                return self.current - 1
            else:
                raise StopIteration

    # Using the custom iterator
    my_iter = MyIterator(1, 5)
    for number in my_iter:
        print(number)
        

In this example, we create a custom iterator class MyIterator that takes a start and end value. The __next__() method returns the next number in the sequence, and when the end is reached, it raises the StopIteration exception to indicate that the iteration is complete.

Output:

    1
    2
    3
    4
    5
        

Using Built-in Iterators

Python provides several built-in iterators, and you can iterate over various types of collections like lists, tuples, and dictionaries directly without needing to create a custom iterator. These collections implement the __iter__() and __next__() methods automatically.

Example 2: Using an Iterator with a List

    numbers = [10, 20, 30, 40, 50]
    numbers_iter = iter(numbers)

    # Using the iterator
    print(next(numbers_iter))  # Output: 10
    print(next(numbers_iter))  # Output: 20
    print(next(numbers_iter))  # Output: 30
        

In this example, we use the built-in iter() function to create an iterator from the list numbers. We can then use the next() function to retrieve the next item from the list.

Output:

    10
    20
    30
        

Example 3: Iterating Over a Dictionary

    my_dict = {"a": 1, "b": 2, "c": 3}
    dict_iter = iter(my_dict)

    # Using the iterator
    print(next(dict_iter))  # Output: a
    print(next(dict_iter))  # Output: b
    print(next(dict_iter))  # Output: c
        

In this example, we iterate over the keys of the dictionary my_dict using the iterator created with the iter() function. By default, the iterator will return the keys.

Output:

    a
    b
    c
        

Understanding the StopIteration Exception

The StopIteration exception is a built-in exception that is raised when there are no more items to return from an iterator. It signals that the iteration is complete, and Python automatically handles this when using loops like for.

Example 4: StopIteration Example

    my_iter = MyIterator(1, 3)
    print(next(my_iter))  # Output: 1
    print(next(my_iter))  # Output: 2
    print(next(my_iter))  # Output: 3
    print(next(my_iter))  # Raises StopIteration
        

In this example, after iterating through all the values (1, 2, and 3), calling next() again raises the StopIteration exception because there are no more values left to iterate over.

Using Iterators in Loops

In Python, you don't usually need to manually call the next() function when using iterators in loops. The for loop automatically handles the StopIteration exception for you.

Example 5: Iterating with a for Loop

    for number in MyIterator(1, 3):
        print(number)
        

This example demonstrates using the for loop to iterate over the MyIterator instance. The loop automatically stops when the iteration is complete.

Output:

    1
    2
    3
        

Conclusion

Iterators are an essential part of Python, allowing you to traverse through collections of data in a memory-efficient and readable way. By implementing the __iter__() and __next__() methods, you can create custom iterators. Additionally, Python provides built-in iterators for common collections like lists and dictionaries. Understanding iterators and how to use them properly can help you write more efficient and Pythonic code.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java