Why Python does *SLICING* the way it does??

Terry Hancock hancock at anansispaceworks.com
Wed Apr 20 11:40:44 EDT 2005


On Wednesday 20 April 2005 07:52 am, Antoon Pardon wrote:
> Personnaly I would like to have the choice. Sometimes I prefer to
> start at 0, sometimes at 1 and other times at -13 or +7.

Although I would classify that as a "rare use case".  So, it "ought
to be possible to do it, but not necessarily easy". Which
Python obliges you on --- you can easily create a relocatable list
class that indexes and slices anyway you see fit, e.g.:

>>> class reloc(list):
...     def __init__(self, start, contents=()):
...         self.start = start
...         for item in contents:
...             self.append(item)
...     def __getitem__(self, index):
...         if isinstance(index, slice):
...         if (not (self.start <= index.start < self.start + len(self)) or
...             not (self.start <= index.stop  < self.start + len(self))):
...             raise IndexError
...             return self.__class__.__base__.__getitem__(self, slice(index.start-self.start, index.stop-self.start, index.step))
...         else:
...         if  not (self.start <= index < self.start + len(self)):
...             raise IndexError
...             return self.__class__.__base__.__getitem__(self, index - self.start)
...
...
>>>
>>> r = reloc(-13, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'])
>>> r[0]
'n'
>>> r[-12]
'b'
>>> r[-13]
'a'
>>> r[-14]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 14, in __getitem__
IndexError
>>> r[0]
'n'
>>> r[3]
'q'
>>> r[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 14, in __getitem__
IndexError
>>>

Note that I added the IndexError to avoid the bizarre results you
get due to "negative indexing" in the list base class (now they
would change behavior at -13 instead of at 0, which is counter-
intuitive to say the least).  Better to cry foul if an index out of
range is called for in this case, because it's gotta be a bug.

What do you think, should I send it to Useless Python? ;-)

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list