Python Forum

Full Version: difference between next() and .__next__
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
in the below code:
def g():
    for i in range(3):
        yield i*i
my_g=g()
my_g.__next__()
next(my_g)
#what is difference between .__next__() and next() ?
next() and .__next__() will show next elements to us. what is the difference between them?
Is the usage of them different?
thanks
In a High-Level-View next(object) calls __next__(object).

The function next is implemented in C and AFAIK different Python-Objects do have different implementations of __next__ in C. But the function next() can also run the Python-Implementation of __next__ of an object.

You should not use __next__ directly.
(Oct-13-2023, 06:57 AM)akbarza Wrote: [ -> ]what is the difference between them?
Globally speaking, I would say that next() and iter() are a public interface while __next__() and __iter__() are an implementation interface of the iterator protocol.

Functionally speaking, there is a difference in that next() and iter() accept a second argument as explained in their documentation.
__next__ is a special method.
https://docs.python.org/3/library/stdtyp...r.__next__
https://docs.python.org/3/reference/expr...r.__next__

next() is a built-in function, that calls __next__() method of the first argument you supply. The docs:

Quote:next(iterator)
next(iterator, default)

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
(Oct-13-2023, 07:34 AM)DeaD_EyE Wrote: [ -> ]In a High-Level-View next(object) calls __next__(object).
it calls object.__next__()