Strange range

Ned Batchelder ned at nedbatchelder.com
Sat Apr 2 17:50:23 EDT 2016


On Saturday, April 2, 2016 at 5:40:35 PM UTC-4, Marko Rauhamaa wrote:
> Chris Angelico <rosuav at gmail.com>:
> 
> > On Sun, Apr 3, 2016 at 6:44 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> >> I don't have a problem with a list being a "reiterable." I only was
> >> surprised about range(), which I had thought to be a plain,
> >> down-to-earth iterator. There's barely any other practical use for a
> >> range, I believe.
> >
> > That's Blub's Paradox right there. There are lots of other uses for
> > range(), but you just haven't used them.
> 
> That's why I was looking for counterexamples in the standard library
> sources but couldn't really spot any (apart from a single
> reversed(range())). Maybe I wasn't looking carefully enough.
> 
> As far as I can tell, range() is simply Python's way of implementing
> classical integral "for" loops.

You can easily use range in my double-loop example, or a variant:

    def pairs(n):
        nums = range(n)
        for i in nums:
            for j in nums:
                yield i, j

More importantly, range can be useful as an argument to a function that
doesn't realize it's receiving a range, as in the better way to implement
pairs:

    from itertools import product

    def pairs(n):
        return product(range(n), repeat=2)

By making range an iterable like lots of other things, it's more useful
in these kinds of compositional situations.

--Ned.



More information about the Python-list mailing list