Search This Blog

Friday 31 January 2014

Iterators and Iterable


Hi ,

here I am going to tell about iterators and iterables in Python. Most of the Python developers are getting confuse what is iterator, iterable and when to use it.

Here  I am explaining in brief which may helpful to get basic knowledge of both.


Iterable

"An object capable of return its members one at a time"

Let me explain more clear.,

If any object is returning its item at a time either by iterating or by returning, it is called Iterable.
for example:: list, str, tuple ----> sequence types
                    dict, file ---------> non-sequence types. For more information about data structures, please click here

One can do this, by implementing __iter__()  method for returning items.


Iterators 

"It is an object which is representation of stream of data."
Confused...!

basically, It can be a user defined or pre-defined which will be having data and can able to send those data by using next() method for taking items. Iterator works till the end of the data. If their is no item, then it will raise stopInteration exception. Once the stopIteration exception came, then the loop will exit.

      When we are talking about Iterators, everyone will think about the iterator's data. but consider a situation, where we require iterator object itself. then, how you will pass object itself?

You can do this, by implementing __iter__() method  which will return iterator itself. As mentioned above, if any object is implementing __iter__() method, it is called  "Iterable". i.e., "every iterator is iterable" :)

No comments:

Post a Comment