[Python-ideas] Implement comparison operators for range objects

MRAB python at mrabarnett.plus.com
Wed Oct 12 13:51:16 EDT 2011


On 12/10/2011 18:33, Steven D'Aprano wrote:
> Sven Marnach wrote:
>> There are circumstances, for example in unit testing, when it might be
>> useful to check if two range objects describe the same range.
>> Currently, this can't be done using the '==' operator:
>>
>> >>> range(5) == range(5)
>> False
> [...]
>> All other built-in sequence types (that is bytearray, bytes, list,
>> str, and tuple) define equality by "all items of the sequence are
>> equal". I think it would be both more consistent and more useful if
>> range objects would pick up the same semantics.
>
> I can see how that would be useful and straightforward, and certainly
> more useful than identity based equality. +1
>
>
>> When implementing '==' and '!=' for range objects, it would be natural
>> to implement the other comparison operators, too (lexicographically,
>> as for all other sequence types).
>
> I don't agree. Equality makes sense for ranges: two ranges are equal if
> they have the same start, stop and step values. But order comparisons
> don't have any sensible meaning: range objects are numeric ranges,
> integer-valued intervals, not generic lists, and it is meaningless to
> say that one range is less than or greater than another.
>
> Which is greater?
>
> range(1, 1000000, 1000)
> range(1000, 10000)
>
> The question makes no sense, and should be treated as an error, just as
> it is for complex numbers.
>
> -1 on adding order comparison operators.
>
>
>
> Aside:
>
> I'm astonished to see that range objects have a count method! What's the
> purpose of that? Any value's count will either be 0 or 1, and a more
> appropriate test would be `value in range`:
>
>  >>> 17 in range(2, 30, 3) # like r.count(17) => 1
> True
>  >>> 18 in range(2, 30, 3) # like r.count(18) => 0
> False
>
In Python 2, range returns a list, and lists have a .count method.
Could that be the reason?



More information about the Python-list mailing list