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.
               y =iter(x)
         #gives output 1
         #gives output 2
                till   #gives output 5
   after this it will throw StopIteration (error)


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.