0

I'm new to Python and was looking for a good explanation on the below challenge. Specifically this:

lst[end+1:]

Maybe someone could write a method that's not condensed into one line?

The challenge is as follows:

* 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)*

They then answer the question with:

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

print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))

#output
[4, 16, 23, 42]

I've tried breaking up the answer and looking up different methods online. So far this is the closest example I've found but doesn't explain much: https://stackoverflow.com/a/509377/14116764

  • What exactly about it are you confused by? Do you know what slicing is? Are you unclear on the syntax? – ddejohn Mar 25 '22 at 02:15
  • You have to understand how Python indexes a list. Conceptually, the indices point to somewhere _in front of_ an element. Here's a good description with visual aids: https://www.learnbyexample.org/python-list-slicing/ – pepoluan Mar 25 '22 at 02:26
  • maybe first use `print()` to display `lst[end+1:]` for different `end` and compare it with original `lst` - this way you will see how it works. – furas Mar 25 '22 at 02:29
  • without slice you would have to create new list, and run two `for`-loops to copy elements from `lst` ot new list: first to copy elements before `start`, and second to copy elements after `end`. And finally you would have to return new list. – furas Mar 25 '22 at 02:32

1 Answers1

3

This is precisely how any Python programmer would write it.

list[:start] is all the elements from 0 (inclusive) to start (exclusive). list[end + 1:] is all the elements from index end + 1 to the end of the array. + concatenates them together.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22