Question

Is there a method for list that does what the python 2 list.__delslice__ does? There is a __delitem__ but it seems it only deletes one item instead of from x to y so here is an example of what I want to do

somelist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
somelist.__delslice__(4, len(somelist))
print(somelist)
# output: [1, 2, 3, 4]

It seems they may have removed this from python 3, did they? If not what is it now called or is there a module that has it?

Was it helpful?

Solution

According to Python 2.7 - object.__delslice__ documentation:

Called to implement deletion of self[i:j]. Same notes for i and j as for __getslice__(). This method is deprecated. If no __delslice__() is found, or for extended slicing of the form self[i:j:k], a slice object is created, and passed to __delitem__(), instead of __delslice__() being called.

So, call the __delitem__ with slice object:

>>> somelist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> somelist.__delitem__(slice(4, len(somelist)))
>>> somelist
[1, 2, 3, 4]

BTW, you can use None in place of len(somelist):

>>> somelist.__delitem__(slice(2, None))
>>> somelist
[1, 2]

UPDATE

You can use del statement with slice:

del somelist[2:]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top