- Define the function to accept three parameters: the list, the starting index, and the ending index
- Get all elements before the starting index
- Get all elements after the ending index
- Combine the two partial lists into the result
- Return the result
Notice the start and end arguments for your function are indices?
Lets walk through your function and try to figure out what it’s doing.
def remove_middle(lst, start, end):
i = start
while i <= end:
i += 1
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
Our function takes 3 positional arguments lst, start and end. With the current print statement using to test this:
lst= [4, 8, 15, 16, 23, 42]
start = 1
end = 3
Bearing that in mind, lets follow the logic of your code and see what it’s doing
The first time the loop runs you start at index 1 (remember indexing starts at 0!)
We take our the list passed to our function, remove the element at index 1 and increase the index by 1.
Now when the loop runs again it is not using the same copy of our list! Remember you both removed an element at index i and increased the index by 1 !
So when the loop runs again:
start = 2
end = 3
lst = [4, 15, 16, 23, 42]
So if we do the same thing again what do you think will happen?
As @lisalisaj already gave you, the solution is slicing and combing the lists.