Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests - Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests -

Difference Between Iterable and Iterator in Python

In this article, we will discuss the difference between iterable and iterator in Python. But before we do that, let us first know a bit more about them individually.

What is an Iterable?

An Iterable is basically an object that any user can iterate over. We can generate an iterator when we pass the object to the iter() method.

What is an Iterator?

An Iterator is also an object that helps a user in iterating over another object (that is iterable). We use the __next__() method for iterating. This method helps iterators return the next item available from the object.

Remember that every iterator is basically iterable, but vice versa is not always true. For instance, a list can be iterable but not an iterator. We can create an iterator from an iterator using the iter() function. To make it happen, the classes of any object require either an __iter__ method, which basically returns an iterator or a method __getitem__ that has sequential indexes beginning with 0.

When we execute a loop, we use the inter() statement calls on the object that loops over. In case this call becomes successful, an iterator object defining the __next__() will return. It accesses the elements present in an object- one at a time.

If there are no further elements, then the method __next__() will raise an exception to StopIteration. As soon as the fort loop catches this exception, it will immediately terminate.

Difference Between Iterable and Iterator in Python

Here is a list of the differences between Iterable and Iterator in Python.

Parameters Iterable Iterator
Meaning and Definition An Iterable is basically an object that any user can iterate over. An Iterator is also an object that helps a user in iterating over another object (that is iterable).
Method Used We can generate an iterator when we pass the object to the iter() method. We use the __next__() method for iterating. This method helps iterators return the next item available from the object.
Inter-Relation Every iterator is basically iterable. Not every iterable is an iterator.

Keep learning and stay tuned to get the latest updates on GATE Exam along with GATE Eligibility Criteria, GATE 2023, GATE Admit Card, GATE Application Form, GATE Syllabus, GATE Cut off, GATE Previous Year Question Paper, and more.

Comments

Leave a Comment

Your Mobile number and Email id will not be published.

*

*