Looking for python Answers? Try Ask4KnowledgeBase
Looking for python Keywords? Try Ask4Keywords

Python Language .next() method on iterators renamed


Example

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

Python 2.x2.3
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.

Python 3.x3.0
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.