Iterables and Iterators
Once upon a time there lived two people , iterable and iterator......
Hello Everyone Once Again!
We often get confused with iterables , iterators and we come across these words quite often so let us learn about these words in detail.
Iterables are those objects which can be iterated over, one by one you can access the elements/items of the objects.
a) String Object, a = “Iterables” , we can access all the elements of object a either
(i). using indexing method
: a = “I”,
:a = “t”,
………a = “s”
b). b = 21.9
Note: Try for list, set, tuple, int, and dictionary as well and check which are iterable objects.
Now we have a clear understanding of iterables let us move on to Iterators.
Iterators are those objects which are used to iterate over iterables . Iterators can be created by using iter() method by passing iterable object in it.
Iterators use next() method to return the next element of the object.
When executed for the very first time, next() returns the element present at 0 index.
(i).When a for loop is executed, it calls iter() method on the object. If this call is successful an iterator object gets created which can be used to iterate over the iterable object and next() method gets imposed which accesses the elements of the object but one element at a time . This process continues until next() reaches the very last element and raises an exception - – StopIteration. For loop gets terminated as soon as – StopIteration exception is raised.
(ii).All iterators are iterables but not all iterables are iterators.
I hope the concepts of iterables and Iterators are clear.
Please let me know if in case you encounter any error in the explanation.