Strange range

Marko Rauhamaa marko at pacujo.net
Fri Apr 1 11:43:01 EDT 2016


Chris Angelico <rosuav at gmail.com>:

> On Sat, Apr 2, 2016 at 1:34 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
>> However, doesn't that extra level of indirection seem like an odd
>> choice?
>
> No; a range object is an entity in itself. You can test if something's
> within the range:
>
>>>> 5 in range(2,10)
> True
>>>> 5 in range(2,10,2)
> False
>
> You can ask how many numbers are in the range:
>
>>>> len(range(2,10,2))
> 4
>
> You can even ask what position a number would be in, if you index
> through the range:
>
>>>> range(3,100,3).index(57)
> 18
>
> Iterators can't do any of this, except the 'in' check, which is
> destructive and O(N).

I can't think of a situation where I would have needed those things. I'm
hard-pressed to find an example of noniterator usage of range in the
standard library, for example. Here the only counterexample that caught
my eye among the first couple of hundred of occurrences:

   reversed(range(len(self)))


Marko



More information about the Python-list mailing list