Strange range

Marko Rauhamaa marko at pacujo.net
Fri Apr 1 16:14:42 EDT 2016


Erik <python at lucidity.plus.com>:

> On 01/04/16 15:34, Marko Rauhamaa wrote:
>> Chris Angelico <rosuav at gmail.com>:
>>
>>> *A range object is not an iterator.*
>>
>> We now have learned as much.
>>
>> However, doesn't that extra level of indirection seem like an odd
>> choice?
>
> [...]
>
> If you write your own class which has an __iter__ method, would you
> [...] expect both iterators to be independent and both return the
> 'foo', 'bar', 'baz' sequence (where that is the hypothetical result of
> iterating over your object)?
>
> If you now replace MyClass() with range(10), why would you expect the
> two iterators to be related?

I simply had thought of range() returning an iterator. I would expect an
iterator to behave like one.

There's a bit of a cognitive dissonance between iterables and iterators.
On the one hand, they behave identically in many contexts. On the other
hand, the distinction is crucial in some special cases.

(Somehow, the difference between iterables and iterators is analogous
with the difference between C's arrays and pointers.)


Marko



More information about the Python-list mailing list