Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the iteration class methods next() and __next__() for, and what is the difference?

I am a little bit lost on python iterators. I occasionally use them, but I don't remember creating one myself. I read from somewhere that I don't remember where, a code like this:

class Foo(object):
    def __init__(self):
        self.something = "initial_value"
    def __iter__(self):
        return self
    def next(self):
        # I don't quite remember what was here :S
        return self.something

I guess __iter__() method supposed to return an iterator, and that iterator should have a next method right? Then what about __next__() method? is it for directly iterating over a class without it returning another iterator with __iter__() method?

like image 778
yasar Avatar asked Aug 28 '11 19:08

yasar


2 Answers

PEP 3114 renamed iterator.next() to iterator.__next__(). This was implemented in version 3.0. The link above contains all the gory details.

like image 102
David Heffernan Avatar answered Sep 24 '22 01:09

David Heffernan


next has been renamed to __next__ in Python 3. As for what it does, it should return the next item, or raise StopIteration if there are no more.

like image 27
Cat Plus Plus Avatar answered Sep 23 '22 01:09

Cat Plus Plus