0

What's wrong with this code?

def remove_middle(lst, start, end):
    for i in range(start, end+1): 
        del lst[i]
    return lst

It should remove all elements place in an index between start and end(inclusive). In the example below, it should return [4, 23, 42] but when I run the code I get [4, 15, 23].

print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
jpp
  • 159,742
  • 34
  • 281
  • 339
python_newbie
  • 75
  • 1
  • 4
  • this is because youre always skipping one element – Azrael Jan 20 '19 at 12:29
  • Note that while the *question* asked in the linked duplicate is somewhat different to this one, one of the answers - namely [this one by Ciro Santelli](https://stackoverflow.com/a/34238688/1709587) - directly addresses why the code exhibited in this question doesn't work. – Mark Amery Jan 20 '19 at 13:01

1 Answers1

-1

Your list changes size each time you delete a value, and you are using indices to delete values. A for loop applies logic successively in each iteration, not simultaneously.

Instead, you can use enumerate with a list comprehension:

def remove_middle(lst, start, end):
    return [val for idx, val in enumerate(lst) if idx not in range(start, end+1)]

The more general case is covered in How to remove items from a list while iterating?

However, in this specific instance, you can use list slicing:

def remove_middle(lst, start, end):
    return lst[:start] + lst[end+1:]
jpp
  • 159,742
  • 34
  • 281
  • 339
  • The linked duplicate (for this very common question) is a lot more detailed, this code has a different result than what's in the question (creates and returns a new list rather than modifying the existing list in-place and then returning it), and a simple slice reassignment would suffice. The code in the question could even be fixed by merely changing `del(lst[i])` to `del(lst[start])`. – TigerhawkT3 Jan 20 '19 at 12:41
  • @TigerhawkT3, Sure. But, sadly, it doesn't answer OP's *specific* question. – jpp Jan 20 '19 at 13:08
  • Sure it does. I like the rather charming explanation in [this answer](https://stackoverflow.com/a/1207485/2617068): "it's a bit like sawing off the tree-branch that you are sitting on." – TigerhawkT3 Jan 20 '19 at 13:12
  • I think the line @TigerhawkT3 quotes above is perhaps a tad cryptic, but [this answer](https://stackoverflow.com/a/34238688/1709587) on the dupe directly answers this question at greater length with a supporting quote from the docs. I agree that the questions aren't quite the same, and was considering voting to reopen after seeing this question in the Reopen queue, but ultimately decided that just linking to that answer in the comments on this question was adequate. – Mark Amery Jan 20 '19 at 13:18
  • @MarkAmery - [This](https://stackoverflow.com/questions/54148684/why-do-i-get-list-index-out-of-range-error-in-this-code) is the same problem as well. It shows up pretty much every day. :) – TigerhawkT3 Jan 20 '19 at 13:23