What are iterators in Python?

Iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods. The __iter__() method, which return the iterator object, and the next() method, which returns the next element from a sequence.
Iterator is an object that can be iterated upon. An object which will return data, one element at a time. An object is called iterable if we can get an iterator from it.
next() function is used to manually iterate through all the items of an iterator. When it reach at the end and there is no more data to be returned, it will raise StopIteration. 
Lists, tuples, strings, dictionaries are built in objects which implement the iteraror protocol.

For example:--

>>> sample_list = [1, 4, 2, 34, 45]
>>> sample_iter = iter(sample_list)
>>> print(next(sample_iter))
1
>>> print(next(sample_iter))
4
>>> print(next(sample_iter))
2
>>> print(next(sample_iter))
34
>>> print(next(sample_iter))
45
>>> print(next(sample_iter))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

 

Total Views: 1584