I don't understand how this list code works

The questions asks to create a function for an output list that will show only the first number and last two numbers of the list.

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

print(middle_numbers_removed([4, 56, 48, 64, 16, 23], 1, 3))

output: [4, 16, 23]

Where did the 1 and 3 go? How did the 4, 16, 23 appear?
Can someone please kindly explain to me how does the return code part works?
Thank you so much!

The important thing to note here is the boundary conditions of list slicing. Otherwise we’re just guessing.

The boundaries are
[inclusive:exclusive] and absence of either imply starting at the head or ending at the tail (inclusive).

So you have lst[:start] is equivalent to lst start from 0 (implied) end 1 before start (because the end boundary is start-exclusive.
And lst[end+1:] is equivalent to lst start from end+1 and finish with the tail (implied).

Print statements are your friend to remove any further doubts. Typing this interactively in some terminal is also your friend.

3 Likes

Does anyone have an alternative explanation?
Appreciate it, thanks!!

pitabread’s explanation is a good one and print() statements are everyone’s friend (I use them all the time).

I think that maybe you’re confused about the parameters of the function(?). You are providing a list and the starting index and ending index, right?

So, with this: print(middle_numbers_removed([4, 56, 48, 64, 16, 23], 1, 3))

  • You’re starting at index 1, which is…56 and the ending point index is 3, which is 64.

  • Your function logic, return lst[:start] will give you the item at the beginning of the list to the stop point, the stop point in the function call is index 1, so that’s the number 56 and it is excluded. What is returned is the number 4 which is at index 0.

  • This part of the function: + 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 the number 64 in the list, +1 to that is 16 and 23.

So, what’s returned is [4, 16, 23]

This can be a tricky one and in order to understand what the logic is doing it might be a good idea to provide different lists and starting & ending indicies so you can understand what the function logic is doing here. For example, what is the output with this, etc?
print(remove_middle([4, 56, 48, 64, 16, 23], 2, 4))

1 Like

Since lists are mutable, we can mutate the list in place by assigning an empty list in place of the designated values to be removed.

>>> a = [4, 56, 48, 64, 16, 23]
>>> start = 1
>>> end = 3
>>> a[start:end+1] = []
>>> a
[4, 16, 23]
>>> 

Does that simplified logic work for you?

1 Like

Thank you all for taking the time to explain to a noob like me!
Really appreciate it!! :slight_smile:

2 Likes