Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an iterable object not an iterator?

Here is my code:

from collections import deque  class linehistory:     def __init__(self, lines, histlen=3):         self.lines = lines         self.history = deque(maxlen=histlen)      def __iter__(self):         for lineno, line in enumerate(self.lines,1):             self.history.append((lineno, line))             yield line      def clear(self):         self.history.clear()   f = open('somefile.txt') lines = linehistory(f) next(lines) 

Error:

Traceback (most recent call last): File "<stdin>", line 1, in <module>     TypeError: 'linehistory' object is not an iterator 

I have no idea why the linehistory object is not an iterator since it has already included __iter__ method in the class.

like image 648
pipi Avatar asked Nov 27 '15 11:11

pipi


People also ask

Can an iterable be an iterator?

Summary. An iterable is an object that implements the __iter__ method which returns an iterator. An iterator is an object that implements the __iter__ method which returns itself and the __next__ method which returns the next element. Iterators are also iterables.

What is the difference between iterable and iterator in Python?

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). We can generate an iterator when we pass the object to the iter() method. We use the __next__() method for iterating.

Which is not a iterator in Python?

A list object is not an iterator because it does not have a __next__() method.

What is difference between iterable and iterator in Java?

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.


1 Answers

The concept of iteration is well documented in the Python documentation.

In short, "iterable" is the object I want to iterate over, also called the container. This can be a list, a string, a tuple or anything else which consists of or can produce several items. It has __iter__() which returns an iterator.

An "iterator" is the object which is used for one iteration. It can be seen as a kind of "cursor". It has next() (in Python 2) or __next__() (in Python 3) which is called repeatedly until it raises a StopIteration exception. As any iterator is iterable as well (being its own iterator), it also has __iter__() which returns itself.

You can get an iterator for any iterable with iter(obj).

In your example, linehistory (which should be written LineHistory) is iterable as it has an .__iter__(). The generator object created with this is an iterator (as every generator object).

like image 177
glglgl Avatar answered Sep 23 '22 05:09

glglgl