Sunday, August 30, 2020

Iterable and Iterator in Python using Aladdin story.

 

Generally we use for-loops to iterate or traverse across the elements within a List or Tuples.


In the for-loop after processing the first element in the list control moves to the next element , this process of traveling from one element to other is called Iteration. For loop works in the same way for Tuples,  Dictionaries, Strings and Sets.

There are two ways to do the same iteration process without using For-Loop. The first method is Indexing 



But this indexing method can be used only for List,Tuples and strings.They cannot be used for Sets and Dictionaries because they are unordered.


 

Iterator Protocol:

The second method we can use is Iterator protocol. Iterator protocol is nothing but working with Iterator and Iterable. Most of us are confused with these two terms Iterable and Iterator.

Let’s have a close look at them now.


Everything that we can loop over is called a Iterable. In the above fig of for Loop list is an iterable.

Now these Iterables do give us the Iterators. They do give these iterators using a function Iter().Iterable usually call this Inbuilt function iter() and generate the Iterator. Using this Iterator we can traverse across the individual elements in the Iterable.

Let’s use our friend Aladdin to explain this Iterable concept.

Consider Aladdin as the Literable and the Genie as the iterator which does things for Aladin.Aladdin brings the Genie out using the Magic lamp, so now the magic lamp is our ITER() object.


 

 

 Aladdin → Iterable

Magic Lamp → Iter()

Genie → Iterator


In the above example the list is the iterable and it uses the iter(list) function to create an iterator for list. Now we can use the Next(iterator) to extract individual element of the iterable.

Let's meet again for another post on Generators.

 

 
 
 

 

 

No comments:

Post a Comment

My Logo