It’s actually the other way around… An empty list is being assigned to replace a range (slice) in the list.
Compare,
>>> def remove_middle(lst, start, end):
lst = lst[:start] + lst[end + 1:]
return lst
>>> remove_middle([4, 8, 15, 16, 23, 42], 1, 3)
[4, 23, 42]
to,
>>> def remove_middle(lst, start, end):
lst[start:end + 1] = []
return lst
>>> remove_middle([4, 8, 15, 16, 23, 42], 1, 3)
[4, 23, 42]
>>>
The first method reconstructs the string with front and back slices that exclude the middle. The second mutates the middle slice. Both approaches return the same result when supplied a list.
It follows that something this general depends upon valid inputs.
- verify that
lst
is indeed a list
object
- verify that the list has some length
- verify that
start
and end
are in range
- verify that
end
is greater than start
Since the function uses slices it may not be necessary to the validate the length; let’s see…
>>> remove_middle([], 1, 3)
[]
>>>
The first approach will also take a string.
>>> def remove_middle(obj, start, end):
obj = obj[:start] + obj[end + 1:]
return obj
>>> remove_middle('9876543210', 1, 3)
'9543210'
>>>
for this one we could add,
- verify that the object is a string (when not a list)
We should be mindful that invalid index inputs will not raise any exceptions since we’re working with slices. Invalid indices are ignored.
>>> remove_middle('9876543210', 11, 13)
'9876543210'
>>>
That’s all the more reason to have our own validation code.