Python List Challenge


#1

Hi

Just wondering if anyone can help me understand this challenge.

The challenge asks the following:

Create a function named remove_middle which has three parameters named lst , start , and end .

The function should return a sub-list of lst with all elements with index between start and end removed (inclusive).

For example, the following code should return [4, 23, 42] because elements at indices 1 , 2 , and 3 have been removed:

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

The correct code is as follows:

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

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

Issue:

I don’t understand why the “+1” is included or what it is doing in this code.

Thanks

Gurpal


#2

Considering what information is needed there, and what information is provided by end should answer that, shouldn’t it?

Maybe you’re really wondering what the slice arguments mean, but then that gives you something you can find out too.


#3

gurpal89,

Without the +1 added to end in lst[end+1:], your code’s output will look like the following:

[4, 16, 23, 42]

Try lst[end:] and you’ll see this printout. The +1 makes it so that it will only print out the one number in between which is 23, rather than also including 16 as well.

Cheers