How Python works: What do you know about support for negative indices?
Terry Reedy
tjreedy at udel.edu
Fri Sep 10 17:13:55 EDT 2010
On 9/9/2010 9:37 PM, Raymond Hettinger wrote:
> The docs guarantee that Python's builtin sequences implement support
> for negative indices (
http://docs.python.org/dev/reference/expressions.html#subscriptions
The relevant paragraphs are
"
For built-in objects, there are two types of objects that support
subscription:
If the primary is a mapping, the expression list must evaluate to an
object whose value is one of the keys of the mapping, and the
subscription selects the value in the mapping that corresponds to that
key. (The expression list is a tuple except if it has exactly one item.)
If the primary is a sequence, the expression (list) must evaluate to an
integer. If this value is negative, the length of the sequence is added
to it (so that, e.g., x[-1] selects the last item of x.) The resulting
value must be a nonnegative integer less than the number of items in the
sequence, and the subscription selects the item whose index is that
value (counting from zero).
"
Reading the third paragraph out of context, one can miss the restriction
to built-in objects. I had assumed that the conversion using len(), when
available, happened prior to the __getitem__ call. I believe I need to
add the restriction in my discussion of negative indexing in my book. I
would like the above rewritten something like the following:
"
Two types of built-in objects support subscription as primaries:
mappings and sequences.
For built-in mappings, the....
For built-in sequences, the ...
"
The second paragraph was written before defaultdict and does not apply
to them. I presume that it is an extension rather than built-in class
for the purpose of the Reference.
> Hope you all found this to be informative,
Definitely. I save a copy for future reference.
--
Terry Jan Reedy
More information about the Python-list
mailing list