Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f77c1d6

Browse files
committed
Clarify where support for negative indices fall in the language hierarchy.
1 parent 476a31e commit f77c1d6

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

Doc/reference/expressions.rst

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -518,11 +518,18 @@ whose value is one of the keys of the mapping, and the subscription selects the
518518
value in the mapping that corresponds to that key. (The expression list is a
519519
tuple except if it has exactly one item.)
520520

521-
If the primary is a sequence, the expression (list) must evaluate to an integer.
522-
If this value is negative, the length of the sequence is added to it (so that,
523-
e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value must be a
524-
nonnegative integer less than the number of items in the sequence, and the
525-
subscription selects the item whose index is that value (counting from zero).
521+
If the primary is a sequence, the expression (list) must evaluate to an integer
522+
or a slice (as discussed in the following section).
523+
524+
The formal syntax makes no special provision for negative indices in
525+
sequences; however, built-in sequences all provide a :meth:`__getitem__`
526+
method that interprets negative indices by adding the length of the sequence
527+
to the index (so that ``x[-1]`` selects the last item of ``x``). The
528+
resulting value must be a nonnegative integer less than the number of items in
529+
the sequence, and the subscription selects the item whose index is that value
530+
(counting from zero). Since the support for negative indices and slicing
531+
occurs in the object's :meth:`__getitem__` method, subclasses overriding
532+
this method will need to explicitly add that support.
526533

527534
.. index::
528535
single: character

0 commit comments

Comments
 (0)