.next method on iterators renamed

suggest change

In Python 2, an iterator can be traversed by using a method called next on the iterator itself:

g = (i for i in range(0, 3))
g.next()  # Yields 0
g.next()  # Yields 1
g.next()  # Yields 2

In Python 3 the .next method has been renamed to .__next__, acknowledging its “magic” role, so calling .next will raise an AttributeError. The correct way to access this functionality in both Python 2 and Python 3 is to call the next function with the iterator as an argument.

g = (i for i in range(0, 3))
next(g)  # Yields 0
next(g)  # Yields 1
next(g)  # Yields 2

This code is portable across versions from 2.6 through to current releases.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents