Strange range

Chris Angelico rosuav at gmail.com
Fri Apr 1 10:45:00 EDT 2016


On Sat, Apr 2, 2016 at 1:34 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Chris Angelico <rosuav at gmail.com>:
>
>> *A range object is not an iterator.*
>
> We now have learned as much.
>
> 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).

ChrisA



More information about the Python-list mailing list