Python - Manual Iteration: iter and next

Introduction

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 X.next() on Python 2.X).

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

Demo

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

f = open('main.py') 
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: f.next()]
# from  w  w w  .  java2  s . co m

Result

Related Topic