What is Iterable,iterator in Python?
Adarsh Rawat
Posted on November 10, 2021
First , we have to understand what is itertors, and why it is used?
Iterator :-
An iterator is an object that contains a countable number of values, in simple words an iterators stores numbers of values,
through which we can iterated upon (traversing over the values).
In Python an iterator is an object which implements the iterator protocol, which consist of the methods iter() and next().
Iteratble :-
objects like (strings, list, tuple, sets, dict) are all iterable (container of values).
Iterator :-
each of above iterable has an iter() method which can be used to get iterator of that particular object i.e, for list we get list_iterator object , for tuple we get tuple_iterator and so on...
let us understand with an example
>>> student_name = ['ram','shyam','john','harry','ravi']
>>> student_iter = iter(student_name)
>>> student_iter
<list_iterator object at 0x000001E7C37E1F30> # list_iterator object
>>>
>>> print(next(student_iter))
ram
>>> print(next(student_iter))
shyam
>>> print(next(student_iter))
john
>>> print(next(student_iter))
harry
>>> print(next(student_iter))
ravi
Using the next(iterable) we can move over elements in the iterator, Remeber on important in iterator object does not have any exception handler , so if we try to call next() ,when we are on the last element, it will throw an StopIteration Exception
the last element in the list is 'ravi' and we are currently on ravi, then let's see what happen what happen if we call next().
>>> print(next(student_iter))
ravi
>>> print(next(student_iter))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
There are mutiple ways to handle this StopIteration Exception
let's see each one of them.
1. We can use try and except block
>>> next(student_iter)
'ravi'
>>> try:
... print(next(student_iter))
... except StopIteration:
... print("StopIteration Exception Handled")
...
StopIteration Exception Handled
>>>
Here, we have handled the exception use try and except block,
it is still a solution to the block , but at the same time , every time we have to use extra lines of code whenever we use next() on the last element.
2. Using for loop
>>> for student in student_iter:
... print(student)
...
ram
shyam
john
harry
ravi
>>>
for loop internally handles the StopIteration Excetion whenever it next() called on the last element.
- By Passing Second Argument in next(iterable,sentinel) you can think sentinel as the default value return whenever *next * called on the last element.
>>> student_name = ['ram','shyam','john','harry','ravi']
>>> student_iter = iter(student_name)
>>> next(student_iter,None)
'ram'
>>> next(student_iter,None)
'shyam'
>>> next(student_iter,None)
'john'
>>> next(student_iter,None)
'harry'
>>> next(student_iter,None)
'ravi'
>>> next(student_iter,None)
>>>
You can see that ,we passed second argument as None , so when we called next on the last element, it does not throw the StopIteration Excetion instead it return the sentinel (default value). In this way we don't don't have to write extra lines of code , only have to pass the second argument.
That's it for now,
i think it would to enough for now,
I will cover some advance topics about iterator in python in the
next article ,*(types of iterators in python, and which is the most optimal one to use).
Posted on November 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024