Python - Data Type Iteration protocol

Introduction

Iteration in Python is based on two objects, used in two distinct steps by iteration tools:

  • The iterable object which returns iterator object
  • The iterator object returned by the iterable which has the __next__() function

Demo

L = [1, 2, 3] 
I = iter(L)                    # Obtain an iterator object from an iterable 
print( I.__next__() )                   # Call iterator's next to advance to next item 
print( I.__next__() )                   # Or use I.next() in 2.X, next(I) in either line 
print( I.__next__() )
print( I.__next__() )

Result

Related Topic