Remove Middle Challenge

I am trying to complete the following challenge:
Create a function named remove_middle which has three parameters named lst , start , and end .

The function should return a list where all elements in lst with an index between start and end (inclusive) have been removed.

For example, the following code should return [4, 23, 42] because elements at indices 1 , 2 , and 3 have been removed:
remove_middle([4, 8 , 15, 16, 23, 42], 1, 3)

Now I understand the solution given but I wanted to try and do my own solution using a while loop and this is the code I have.

def remove_middle(lst,start,end):

i = start

while i <= end:


i += 1

return lst


When I try the code out it return [0,1,4,6] but it should return [0,1,5,6,7] any help would be appreciated.

Removing from a list you are looping over is tricky business, lets say you have the following list:

a   b   c # values in the list
0   1   2 # indexes

and you remove the first element, you end up:

_   b   c 
0   1   2 

where the underscore represents the absence of a value. Except that the list can’t exists in this state, so everything shifts to the left:

b   c
0   1

this combined with a loop is problematic. You increase i, but you skip an element because of the shift that occurs

there are possible solutions like looping in reverse. But list slicing would be much better here :slight_smile:

1 Like

removing values in a list youre looping through is very error prone so a for loop would definitely be better or have a look at list splices for example:

start_ind = lst.index(start)
end_ind = lst.index(end) + 1

return lst[:start_ind] + lst[end_ind]

why use .index()? you are already given the indexes, you don’t need the values from the list to use them as indexes