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

4
  • What exactly about it are you confused by? Do you know what slicing is? Are you unclear on the syntax? Commented Mar 25, 2022 at 2: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: learnbyexample.org/python-list-slicing Commented Mar 25, 2022 at 2: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. Commented Mar 25, 2022 at 2: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. Commented Mar 25, 2022 at 2:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.