Sunday 25 December 2016

What is iterator in Python?

The iterator function(iter()) takes an iterable object and returns a iterator.And it will return one object at a time.
What is an iterable?
Anything such as a list, set,range or dict with a built-in protocol for visiting each element in a certain order is Iterable.
Example:x=[1,2,3,4,5]
               y =iter(x)
               y.next()    #gives output 1
               y.next()    #gives output 2
                till y.next()   #gives output 5
   after this it will throw StopIteration (error)

Important:

1.Iterators are implemented as classes.
2.Iteration is a process implying iterables (implementing the __iter__() method) and iterators (implementing the __next__() method).

Why use iterators?

1.Iterators save resources.