__getitem__ and slices
Daniel Silva
dsilva at ccs.neu.edu
Wed Jan 29 17:16:32 EST 2003
The Python Reference Manual states:
"The following methods can be defined to implement container objects. ...
The first set of methods is used either to emulate a sequence or to emulate
a mapping; the difference is that for a sequence, the allowable keys should
be the integers k for which 0 <= k < N where N is the length of the
sequence, or slice objects, which define a range of items. ...
__getitem__(self, key)
Called to implement evaluation of self[key]. For sequence types, the
accepted keys should be integers and slice objects."
http://www.python.org/doc/current/ref/sequence-types.html
This code, however, fails:
>>> [1,2,3].__getitem__(slice(1,2))
Traceback (most recent call last):
File "<pyshell#17>", line 1, in ?
[1,2,3].__getitem__(slice(1,2))
TypeError: an integer is required
whereas this works:
>>> [1,2,3][1:2]
[2]
It was my understanding that primary[start:stop] would be translated into
primary.__getitem__(slice(start,stop)). Either the List __getitem__ method
or the documentation for sequences seems incorrect.
- Daniel
More information about the Python-list
mailing list