Today, during the interview, I discovered that the interviewer has a big conflict between iterator and iterable. So, I decided to write this post.
Firstable, let’s start by presenting the context, the question was to locate the error in the below code
>>> l = range(3) >>> l [2] = 10 >>> l = (1, 3, 4)
The interviewer think that there is two errors in the last two lines:
- he think that range returns a non mutable object so we can not modify its value
- he think that we can not assign l to another object
However, In Python 2.x, range returns a list, and not an iterator, So the second line is true in Python 2.x. In the case of the third line, It’s acceptable in all python versions.
>>> l = xrange(3) >>> l [2] = 10 >>> l = (1, 3, 4)
For the precedent code, the second line raise a TypeError exception, because xrange returns an iterator object not an iterable object
Conclusion:
They are iterable, but they are not iterators. They can be passed to iter()
to get an iterator for them either implicitly (e.g. via for
) or explicitly, but they are not iterators in and of themselves. An iterator is an object representing a stream of data. It implements the iterator protocol:
- __iter__ method
- next method
On the other hand, Iterable object implements the __iter__ method that returns an Iterator object.