Story of Iterables And Iterators

#iterables #and #iterators

Swati Pandey Apr 28 2021 · 1 min read
Share this

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.

For example:

a) String Object, a = “Iterables”  , we can access all the elements of object a either

(i). using indexing method

: a[0] = “I”,

:a[1] = “t”,

………a[8] = “s”

(ii).using lo

Iterating over elements using For Loop

b). b = 21.9

Float Objects are not iterables

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.

For example:

Use Of iter()

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.

Use of next()
next() accesses one element at a time
next(): exception encountered when all the elements get exhausted


(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.

Read next