I work on a class with and embedded list.
class a:
def __init__(self, n):
self.l = [1] * n
def __getitem__(self, i):
return self.l[i]
def __delitem__(self, i):
print type(i)
print i
I want to use the del operator with the full syntax of slices:
p = a(10)
del p[1:5:2]
The __delitem__ receives a slice object if the parameter is not a single index. How can I use the slice object to iterate through the specified elements?
The
indicesmethod of the slice object will, given the length of the sequence, provide the canonical interpretation of the slice that you can feed toxrange:The use of
slice.indicesmakes sure that you get correct behavior in cases pointed out by Dunes. Also note that you can pass the slice object tolist.__delitem__, so if you only need to do some preprocessing and delegate actual deletion to the underlying list, a “naive”del self.l[i]will in fact work correctly.operator.indexwill make sure that you get an early exception if your__delitem__receives a non-slice object that cannot be converted to an index.