Home > Backend Development > Python Tutorial > How Do Python's `__iter__` and `__next__` Methods Enable Iterator Creation?

How Do Python's `__iter__` and `__next__` Methods Enable Iterator Creation?

Patricia Arquette
Release: 2025-01-02 19:19:43
Original
843 people have browsed it

How Do Python's `__iter__` and `__next__` Methods Enable Iterator Creation?

Creating Iterators in Python

Python iterators are objects that adhere to the iterator protocol, featuring the __iter__() and __next__() methods.

iter Method:

The __iter__() method returns the iterator object, automatically invoked at the start of loops.

next Method:

The __next__() method retrieves the subsequent value and is implicitly called during loop increments. It raises a StopIteration exception when no more values are available, which is detected by loop constructs and used to cease iteration.

For instance, consider the following simplistic counter class:

class Counter:
    def __init__(self, low, high):
        self.current = low - 1
        self.high = high

    def __iter__(self):
        return self

    def __next__(self): # Python 2: def next(self)
        self.current += 1
        if self.current < self.high:
            return self.current
        raise StopIteration
Copy after login

When utilizing the Counter:

for c in Counter(3, 9):
    print(c)
Copy after login

The output will be:

3
4
5
6
7
8
Copy after login

Alternatively, generators offer a simpler approach to iterator creation:

def counter(low, high):
    current = low
    while current < high:
        yield current
        current += 1
Copy after login

Employing the generator:

for c in counter(3, 9):
    print(c)
Copy after login

Produces identical output. Internally, the generator resembles the Counter class, supporting the iterator protocol.

For a comprehensive overview of iterators, please refer to David Mertz's article, "Iterators and Simple Generators."

The above is the detailed content of How Do Python's `__iter__` and `__next__` Methods Enable Iterator Creation?. 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