
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Python Iterable and Iterator
What is an iterable?
An iterable can be loosely defined as an object which would generate an iterator when passed to inbuilt method iter(). There are a couple of conditions, for an object to be iterable, the object of the class needs to define two instance method: __len__ and __getitem__. An object which fulfills these conditions when passed to method iter() would generate an iterator.
Iterators
Iterators are defined as an object that counts iteration via an internal state variable. The variable, in this case, is NOT set to zero when the iteration crosses the last item, instead, StopIteration() is raised to indicate the end of the iteration.
Iterable vs Iterators
Let us see an example to check the difference between Iterable and Iterators ?
Basic | Iterable | Iterator |
---|---|---|
What? | An object to iterate over is Iterable. | Iterators are defined as an object that counts iteration via an internal state variable. |
Relation | Every iterator is iterable. | Not every iterable is an iterator. |
Method for Iterating | An object which would generate an iterator when passed to in-built method iter(). | The next() is used for iterating. |
List | A List is iterable. | A List is not an iterator. |
Example
In the below example, we have a Cars class, which is both iterable and iterator. The Cars class is an iterator because it implements ?
__iter__ method returns the object itself,
__next__ method returns the next item from a list
The Cars class is also an iterable because it implements,
__iter__ method returning an object itself, which is an iterator.
Let us now see the example ?
class Cars: def __init__(self): self.rgb = ['bmw', 'audi', 'benz', 'tesla'] self.__index = 0 def __iter__(self): return self def __next__(self): if self.__index >= len(self.rgb): raise StopIteration # return the next car name car = self.rgb[self.__index] self.__index += 1 return car