Python List Challenge

Hi there

Just been working my way through Advanced Python Code Challenges: Lists. I’m slightly confused with the answer to the task listed below:

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:

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

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

My question is how does this remove the elements with an index between ‘start’ and ‘end’?

I thought this would return the elements between ‘start’ and ‘end’ not remove them?

I assume I’m missing something obvious, Lists are something I’m struggling to grasp!

Any help would be greatly appreciated.

no, we want to remove the middle items. So we return the new list with the items before and after the middle.

we take the items at the start/before the middle:

lst[:start]

then we take the items at the end/after the middle:

lst[end+1:]

and concatenate that into a new list (+)

1 Like

To add to what @stetim94 said, an expression like lst[:start] selects everything before the index start. Likewise, and expression like lst[end+1:] selects everything after the index end+1.

1 Like

@stetim94 @codeneutrino

Great, I understand this now.

Appreciate the help!

1 Like

Here, I think you mean everything after end will be selected, not everything after end+1.

1 Like

Yes-oops, sorry my mistake!
@liampage3784097390, yes-an expression like lst[end+1:] selects everything after the index end. The +1 is there because (as far as I know), the ending expression is exclusive.

1 Like