Home > Back-end >  Understanding specific slice method
Understanding specific slice method

Time:03-25

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

CodePudding user response:

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.

  • Related