Python 3: range objects cannot be sliced

John Machin sjmachin at lexicon.net
Sun Jan 25 22:23:20 EST 2009


On Jan 26, 12:08 pm, Terry Reedy <tjre... at udel.edu> wrote:
> Fuzzyman wrote:
> > On Jan 25, 2:28 pm, Alan G Isaac <alan.is... at gmail.com> wrote:
> >> On 1/16/2009 3:13 PM Alan G Isaac apparently wrote:
> >>  > It is documented:
> >>  >http://docs.python.org/3.0/library/stdtypes.html#sequence-types-str-b...
>
> >> But then again, the opposite is also documented,
> >> since `range` is a sequence type.  Quoting:
>
> >>      Sequences also support slicing ...
>
> >>      Some sequences also support “extended slicing”
>
> >> Is this a documentation bug, or a bug in `range`?
> >> (I'd think the latter.)
>
> No range slicing is intended.
>
> > Where does the documentation say that range objects are sequences?
> > They're iterables.
>
> Range objects (2.x xrange objects) were more sequence-like in 2.x. 3.0
> doc still says "There are five sequence types: strings, byte sequences,
> byte arrays, lists, tuples, and range objects" (the miscount has already
> been reported.)
>
> I added a note to
>    http://bugs.python.org/issue4966
> suggesting that ranges be removed from the sequence section.
> I made several other suggestions for improving this sections.
>
> Supportive comments might help get action.

I agree the docs need to be fixed; it's not very sequency at all.
Other comments:

* This error message should not use the s-word, but this may be
unavoidable:
>>> range(10)[1:3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'

* It would be good if the docs said more about what it is meant to be
used for, apart from the obvious "for item in a_range".

You can subscript a range, not that it's very useful:
>>> range(10)[7]
7

It has neither next() nor __next__() method, and appears to be
reusable (which is good, IMO):

>>> x = range(10)
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'range' object has no attribute 'next'
>>> x.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'range' object has no attribute '__next__'
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

It is immutable, and thus can be hashed ... use case?

Cheers,
John



More information about the Python-list mailing list