[Tutor] range as a not-quite-iterator

eryksun eryksun at gmail.com
Sun Aug 4 03:32:19 CEST 2013


On Sat, Aug 3, 2013 at 9:14 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> using py3.3 on win7
>
> I'm reading the Lutz book, and he clearly calls range an iterator in
> the context of Python 3.0, yet when I try
>
> x = range(1,10)
> next(x)
> I get: builtins.TypeError: 'range' object is not an iterator
> And x itself is returned as: range(1, 10)
>
> What am I missing here? Is it an iterator or not?

No, it's not an iterator. It's an iterable. This way it's simple to
reuse a range object concurrently. For example, this creates 3
iterators and grabs values from each:

    from itertools import islice

    r = range(1, 10)
    it = [iter(r) for i in range(3)]

    >>> type(it[0])
    <class 'range_iterator'>

    >>> list(islice(it[0], 5))
    [1, 2, 3, 4, 5]
    >>> list(islice(it[1], 7))
    [1, 2, 3, 4, 5, 6, 7]
    >>> list(islice(it[2], 3))
    [1, 2, 3]
    >>> list(it[0]), list(it[1]), list(it[2])
    ([6, 7, 8, 9], [8, 9], [4, 5, 6, 7, 8, 9])

The range object itself doesn't have to keep track of the state of
each iteration. It just spins off an iterator that handles it. Like
most iterators these get used once and thrown away:

    >>> next(it[0], "It's dead, Jim")
    "It's dead, Jim"


More information about the Tutor mailing list