Home > Backend Development > Python Tutorial > How to Build Custom Iterators in Python Using `__iter__` and `__next__`?

How to Build Custom Iterators in Python Using `__iter__` and `__next__`?

Patricia Arquette
Release: 2024-12-17 14:56:17
Original
854 people have browsed it

How to Build Custom Iterators in Python Using `__iter__` and `__next__`?

Building Basic Iterators in Python

Suppose you have a class that encapsulates a collection of values and you want to create an iterator that allows you to access those values sequentially.

To build an iterator, implement the iterator protocol, which requires defining two methods:

1. __iter__(): Initializes and returns the iterator object itself.

2. __next__(): Returns the next value in the sequence or raises StopIteration if there are no more values.

Example Iterator:

Consider the following class with a list of values:

class Example:
    def __init__(self, values):
        self.values = values

    # __iter__ returns the iterable itself
    def __iter__(self):
        return self

    # __next__ returns the next value and raises StopIteration
    def __next__(self):
        if len(self.values) > 0:
            return self.values.pop(0)
        else:
            raise StopIteration()
Copy after login

Usage:

With this iterator, you can iterate over the values in the Example class:

e = Example([1, 2, 3])
for value in e:
    print("The example object contains", value)
Copy after login

This will print:

The example object contains 1
The example object contains 2
The example object contains 3
Copy after login

Iterator Customization:

As seen in the example above, the iterator's next method can control how values are fetched and returned, providing greater flexibility for customized iterators.

The above is the detailed content of How to Build Custom Iterators in Python Using `__iter__` and `__next__`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template