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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Python Language Question?