Python Iterators(what,iter,next and example)



  • The built-in function iter takes an iterable object and returns an iterator.
  • Each time we call the next method on the iterator gives us the next element. 
  • If there are no more elements, it raises a StopIteration.
  • Iterators are implemented as classes. 
  • Here is an iterator that works like built-in xrange function. 
  • The __iter__ method is what makes an object iterable. 
  • Behind the scenes, the iter function calls __iter__ method on the given object. 
  • The return value of __iter__ is an iterator. 
  • It should have a next method and raise StopIteration when there are no more elements.

>>> x = iter([1, 2, 3])
>>> x
<listiterator object at 0x1004ca850>
>>> x.next()
1
>>> x.next()
2
>>> x.next()
3
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration





No comments:

Post a Comment