Strange range

Steven D'Aprano steve at pearwood.info
Sun Apr 3 00:43:59 EDT 2016


On Sun, 3 Apr 2016 06:44 am, Marko Rauhamaa 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.

I can understand that you were mistaken. It's an easy mistake to make.

But I don't understand why you seem to be insisting that its somehow a flaw
that (x)range is implemented as a "lazy list" instead of an iterator.

If you want an iterator, it's only a single function call away: iter(r).

In the meantime, range objects provide the full sequence API. They're not
quite full lists, as they don't allow arbitrary orderings or arbitrary
items, so any list method which implies that arbitrary items can be
inserted or deleted are not included.

It also acts as a proof of concept that Python supports intelligent, lazy
objects that can produce values on demand.

If you personally don't see any advantage in this, so be it, but you might
not be aware of the history of (x)range:

Guido in 2001: "Nobody uses this extra functionality, and its buggy, let's
get rid of it."

https://www.python.org/dev/peps/pep-0260/

Feature request in 2004: "Membership testing in xrange objects is horribly
slow. Let's add a __contains__ method."

http://bugs.python.org/issue1002085

(Request rejected, because the __contains__ method was removed in 2002.)

Discussion and feature request in 2007: "We really ought to fix that slow
performance of (x)range membership testing..."

http://bugs.python.org/issue1766304


So it's one of those things on the border of useful or not. Those who use
it, miss it when its gone. Those who don't, don't understand why anyone
wants it.



-- 
Steven




More information about the Python-list mailing list