Try to use while loop to pop index but meet unexpected result

Learn Python 3 | Codecademy

Trying to solve a list challenge using following while loop:

def remove_middle(my_list, start, end):
  while start <= end:
     my_list.pop(start)
     start += 1
  return my_list
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))

Outcome of this code is supposed to be [4, 23, 42], but it turns out to be [4, 15, 23]

I just cannot figure out why…

Oh I see why. After using my_list.pop(start), the length of my list and index of each element will change but i wongly deemed it to be the same and still used the old index in the new while loop

Your function should work with any arguments supplied. What happens when you pass other lists and start, stop indicies? Ex: print(remove_middle([5, 7, 19, 2, 49, 50], 1, 4)) ?

I think this is the code they supplied in their solution(?), but you see that it accepts any arguments:

Summary
def remove_middle(lst, start, end):
  return lst[:start] + lst[end+1:]

print(remove_middle([4, 56, 48, 64, 16, 23], 2, 4))
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3)) 
print(remove_middle([7, 17, 52, 3, 24, 2], 2, 4))
print(remove_middle([99, 8, 27, 15, 12, 1, 44], 1, 3))
print(remove_middle([16, 27, 55, 44, 19, 202, 13], 2, 4))
print(remove_middle([5, 7, 19, 2, 57, 50], 1, 3))

>>[4, 56, 23]
[4, 23, 42]
[7, 17, 2]
[99, 12, 1, 44]
[16, 27, 202, 13]
[5, 57, 50]

A really good resource to visualize how your code is executed is Python Tutor.