Python Language Incompatibilities moving from Python 2 to Python 3 .next() method on iterators renamed


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))  # Yields 0  # Yields 1  # 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.