About list slicing

Hello, you’re doing a great service by helping other newbies. I am also a newbie.
I ran this code:

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

but I got [4, 16, 23, 42].

I see you explain the streamlined version as

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

I understand that you’re right, this is the correct answer, however, I do not understand the practical application of lst[end +1:]. Can you please explain that portion of your code again?

I ran this code below to solve the challenge:
def remove_middle(lst, start, end):
return lst[:start] + lst[end+1:]

But I cannot fathom the lst[:start]. To provide a list, say, lst = [0, 1, 2, 3, 12, 14]. If I poll the index at lst[:3], this is the same as lst[0:3]. In other words, 0, 1, and 2 will be returned. But what is the practical application for lst[:start] or lst[0:start]?

You will run into this problem more often, a concept is explained but the immediate practical usage might not be clear. That is okay, that will come with practice and experience.

okay, practical example i recently faced, i had a list of all countries (249 of them), which could be activated/deactivated using check-boxes, however, once a checkbox is disabled its not included within the array, i did briefly considered using some form of list slicing (i needed to figure out which countries when from active to inactive and vice versa)

Didn’t use list slicing in the end, but in other case i might have. You need to know basic concepts like list slicing, you will never know when you need them. And you must consider multiple approaches to solve your problem, to see which best fit the dilemma you are facing.

hope that answered your question

1 Like

Wow, thank you for responding so quickly! Sorry about my late response, I was at my grandparents for the Thanksgiving Break and grandma bans electronics. However, I still do not understand why I need the end+1. I also cannot wrap my head around why it is :start instead of start:

okay, so the list is essential 3 sections:

beginning section, middle section and final section

we want to remove the middle section, which depends on the values of start and end parameter. So what the exercise does it take the beginning sections and final sections, which it then “joins” together using +

which is why its [:start]

we need the values of the beginning section, with start variable as stop value.