Advanced Python Code Challenges: Lists

Hi fellow coders,

I am currently doing the Learn Python 3 course and I have a question regarding the Advanced Python Code Challenges: Lists task number 2.

In the def remove_middle(lst, start, end): function, for subtask 3, I don’t understand why we need to add end+1 to get all the elements after the ending index (inclusive) instead of simply typing end:.

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

The whole task is the following:

  1. Define the function to accept three parameters: the list, the starting index, and the ending index
  2. Get all elements before the starting index
  3. Get all elements after the ending index
  4. Combine the two partial lists into the result
  5. Return the result

Is anyone able to shed any light?

Thanks a bunch!!

1 Like

What was your code? Can you post it?

Let’s say this is your function call:
remove_middle([4, 8 , 15, 16, 23, 42], 1, 3)

the starting index is 1, the end index is 3.

lst[:start] gives you the item at the beginning of the list to the stop point. The stop point above is 1. So, the function will return 4.

lst[end+1:] will give you the end of the list(whatever the number is) plus 1 (ie: moving to the right). The end here is index 3, which is 16 in the list and +1 to that is 23. So, what is returned after removing elements at indicies 1, 2 and 3?
[4,23,42]
I hope that makes sense(?)

What would the result be in this case?
print(remove_middle([7, 17, 52, 3, 24, 2], 2, 4))

1 Like

Hey,

Thanks for your reply!

What I don’t understand is why lst[end:] doesn’t give all the elements after the ending index without the need to include the +1 part. Doesn’t [end:] read as ‘include everything to the right of the ending index’? So, the +1 part is what confuses me.

Thanks again for your help :))

Sure! You’re welcome.:slight_smile:
We’re asked to remove the middle elements, or, those that are between whatever indicies we supply as arguments. in this case elements at indexes 1, 2 & 3 of this list:
(remove_middle([4, 8, 15, 16, 23, 42], 1, 3)) .

lst[end+1:] will return 23 AND 42 b/c of the “:”.

I recommend tweaking the return statement and the arguments that you pass thru the function to see how it works.

what is returned here?

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

Or, here?

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

or here?

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

Thanks again for your help! :slight_smile:

1 Like