Python Forum
difference between next() and .__next__
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
difference between next() and .__next__
#1
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
Reply
#2
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.
akbarza likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(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.
akbarza likes this post
Reply
#4
__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.
akbarza likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Oct-13-2023, 07:34 AM)DeaD_EyE Wrote: In a High-Level-View next(object) calls __next__(object).
it calls object.__next__()
akbarza likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020