Strange range

Ned Batchelder ned at nedbatchelder.com
Sat Apr 2 15:47:01 EDT 2016


On Friday, April 1, 2016 at 10:34:50 AM UTC-4, 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?

I agree that it is surprising (and confusing) at first.  It took me
some getting used to.

Now I think of it like this: An iterable is a thing that could be
iterated, that is, it has a sequence of things.  An iterator holds the
current status of a thing that is being iterated.  For example, the
pages of a book are an iterable (we could iterate over them), and a
bookmark is an iterator for the pages of a book: it knows where we are
in the iteration.

This analogy illuminates an important point: a single iterable can have
a number of active iterators working over it at once, just as a book can
have a number of bookmarks in it at once.

    nums = [1, 2, 3]
    for i in nums:
        for j in nums:
            print i, j

This prints all the pairs of numbers, because the iterator in the first
loop is independent of the iterator(s) in the second loop, even though
they are iterating over the same iterator (the nums list).  Without the
extra indirection of iterators over iterables, this code would get
tangled up.

--Ned.



More information about the Python-list mailing list