[Python-ideas] range

Andrew Barnert abarnert at yahoo.com
Thu Feb 21 18:20:28 CET 2013


On Feb 21, 2013, at 5:35, Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de> wrote:

> Dear all,
> what do you think about allowing the use of operators on ranges?
> 
> I thought of things like:
> a = range(1,10)
> b = range(5,12)
> intersect = a & b     # equivalent to intersect = range(5,10)
> merge = a | b         # equivalent to merge = range(1,12)
> 
> to make this work in more complex cases, like:
> a = range(1,10)
> b = range(12,15)
> merge = a | b         # equivalent to sth. like range(range(1,10),range(12,15))

That means ranges are no longer constant size, no longer have constant- time contains-testing, etc.; it's linear in the number of sub ranges. (And so would intersect and union, for that matter.) 

That's more like a sparse set or an RLE-encoded set or something--which is a useful thing for numerical work (does pandas have an equivalent?), but it's not really a range anymore.

Maybe build a new IntervalSet or something, which can interact with ranges (and itertools.count?) transparently (by treating them as a set of 1), put it on PyPI, and see how many users find themselves wishing that range(1, 10) | range(12, 15) would return an IntervalSet so they wouldn't have to do IntervalSet(range(1, 10)) | range(12, 15). That seems like the best way to find out whether this would be useful in practice.

Also, I think I'd expect difference and symmetric difference if I wanted union, and if you're handling infinite ranges I'd expect complement as well. Plus interaction with single ints as well as ranges and other sets. But that may be excessive feature creep--since I don't have an obvious use for union, I may be imagining things wrong.

> maybe range nesting would be desirable, but the full sequence of values of such
> a nested range could still be calculated on demand.
> 
> Such syntax would allow for the generation of more complex sequences, and, as a
> side-effect, ranges could also be checked for overlap easily:
> if a & b:
>  do_something()

This side effect seems like it would be useful more often than the main effect. I've written a ranges_intersect function in at least two projects, but I've never written an intersect_ranges. (That is, I only need a boolean value.)

> 
> this whole idea is reminiscent, of course, of what's implemented for sets
> already, so like there you could think of
> intersect = a & b as shorthand for intersect = a.intersection(b)
> 
> Opinions?
> 
> 
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list