Python - Manual Iteration: iter and next


To simplify manual iteration, Python has a built-in function, next.

The next function automatically calls an object's __next__ method.

Given an iterator object X, the call next(X) is the same as X.__next__() on Python 3.X (and on Python 2.X).

With files, for instance, either form may be used:


f = open('') 
print( f.__next__() )                   # Call iteration method directly 
print( f.__next__() )

f = open('') 
print( next(f) )                        # The next(f) built-in calls f.__next__() in 3.X 
print( next(f) )                        # next(f) => [3.X: f.__next__()], [2.X:]
#   w w  w  .j  a va  2 s .c  o  m


Related Topic