Python Forum
difference between next() and .__next__ - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: difference between next() and .__next__ (/thread-40916.html)



difference between next() and .__next__ - akbarza - Oct-13-2023

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


RE: difference between next() and .__next__ - DeaD_EyE - Oct-13-2023

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.


RE: difference between next() and .__next__ - Gribouillis - Oct-13-2023

(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.


RE: difference between next() and .__next__ - buran - Oct-13-2023

__next__ is a special method.
https://docs.python.org/3/library/stdtypes.html#iterator.__next__
https://docs.python.org/3/reference/expressions.html#generator.__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.



RE: difference between next() and .__next__ - buran - Oct-13-2023

(Oct-13-2023, 07:34 AM)DeaD_EyE Wrote: In a High-Level-View next(object) calls __next__(object).
it calls object.__next__()