FAQ: Code Challenge: Lists - Remove Middle

#28

This took me a while to figure out. I finally get it now. The +1 at the end is to adjust for the final number “end” to be removed from the function. To some of the other threads, I was tempted to use additional functionality, but I assume there is a method to his madness. This is so far the hardest exercises, primarily because of the wording.

2 Likes
#30

im also having trouble with this, i dont think there was a lesson introducing some of this subjects or at least i cant remember, i have to look at the answer.

#Write your function here
def remove_middle(lst, start, end):
return lst[:start] + lst[end+1:]

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

also, i dont understan what the 1, 3 mean

#31
    remove_middle(lst, start, end)
                  [ ],   1  ,  3
4 Likes
#32

#Write your function here

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

#33

It’s not just you, this section of challenges was very poorly organized. Every single one of them requires knowledge that was not taught in the lessons. Maybe they’re trying to teach us to be resourceful?

1 Like
#34

So if we can use the “+” to add things from a list into another list why cant we use the minus symbol ( - ), in order to remove an area of a list we dont want?

#36

Bro how much did this take for you to write that code? the area_1 is start but the area_2 gives negative number always. i dont know how the fk this code works but it does lol nice

#37

The plus sign is a concatenation operator. Concatenation is a processing of linking two objects: a string to a string, or a list to a list. There is no operation to minus an element from a list, save manual iteration or using a method such del(), .pop(), or .remove().

#38

What you need to understand here is that [:start] gets everything UNTIL start (not including start) , and [end:] gets everything FROM end until the end (including end). But since we want to erase the middle, we don’t want to include end.

Here is what I’ve got:

def remove_middle(lst, start, end):
  first = lst[:start]
  second = lst[(end+1):]
  return first + second
#39

How would I know to use ‘+1’ after [end] for this problem? What does adding a ‘+number’ when I’m slicing lists? Hope this makes some sense.

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

Thanks for the help.

#40

If we use end as given, then the new combined string will contain the letter at index end, which we do not want. We need to exclude all the characters between start and end, including the characters at those indices, hence, end + 1.

Sketch it out on paper to give yourself a better picture.

['abcdefg'][start ('h') 'ijklmnopqr' end('s')]['tuvwxyz']
    .. 6            7                    16    17 ..

Recall that a slice excludes the stop index so when we write, str[:7] it gives abcdefg, and when we write, str[17:] it gives tuvwxyz.

The removed substring should be 10 characters long,

len('hijklmnpqr')    # 10
1 Like
#41

The above post is so full of errors it’s embarrassing.

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

>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> remove_middle(s, 7, 17)
('abcdefgrstuvwxyz', 'hijklmnopq')
>>> a, b = remove_middle(s, 7, 17)
>>> len(a); len(b)
16
10
>>> 

One clearly sees why this question came up. Intuition, or something of that nature. How I plunged headlong in defense with blinders on is my bad. Didn’t feel right afterward so came back for another look see. Lucky I did.

Visualization

>>> def remove_middle(x, h, k):
	return x[:h], x[h:k], x[k:]

>>> l, m, r = remove_middle(s, 7, 17)
>>> '{} {} {}'.format(l, m, r)
'abcdefg hijklmnopq rstuvwxyz'
>>> 

Now we need to get this to work on a list.

>>> l, m, r = remove_middle(list(s), 7, 17)
>>> l + r
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> m
['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']
>>> 
#42

I tried to use delete, because in a previous lesson we were taught the following:
" Emptying a list

There are two ways to empty an existing list. The first way is to just assign the list variable to an empty list. In this case, the old list and its contents are automatically deleted by Python. This is shown in the following code example. list1 = [1, 2, 3, 4, 5, 6, 7 ]
list1 = [ ]
The second method is to use the del() function to delete all the elements of the list. This forces the removal of all the items immediately instead of letting Python delete the contents at some time of its choosing. Both methods produce the same end result which is that the list will be empty of contents.
list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
del list2[:]"

but obviously that command can’t be right with the space between del and list because python hates spaces. can this even work if put in correct syntax?
lst = del(lst[start:end+1]) ?

#43
>>> s
'abcdefghijklmnopqrstuvwxyz'
>>> t = list(s)
>>> del(t[7:17])
>>> t
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> ''.join(t)
'abcdefgrstuvwxyz'
>>> 
>>> t = list(s)
>>> del (t[7:17])     # don't leave out the parens; space is not a problem
>>> ''.join(t)
'abcdefgrstuvwxyz'
>>> 
1 Like
#44

thank you!

I don’t understand this part, though: ‘’.join(t)
I don’t think that was in a lesson yet. what is it supposed to do?

#45

The str.join() method takes a list of strings and concatenates them into a single string. The string object it acts upon is the separator, in this case an empty string.

It can also be used to insert characters into a string…

>>> '-'.join('catnip')
'c-a-t-n-i-p'
>>> 
#46

thanks :slight_smile:

1 Like
#47

I have a question.
this is the code I used:

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

If I didn’t create the new list “rlist” and just used “return lst…etc…” as someone showed above, wouldn’t it have just modified the original list “lst”? Was that the goal, to modified the existing list?

… I keep thinking they want new lists…haha!:upside_down_face:

#48

If you assign the inputted lst to any new variable name, even lst, a copy will be made, and that new variable name will remain local to your function. Your original list will not be changed.
For a function to change a list in place, the list elements must be changed.

EDIT: The above paragraph stands corrected by rtf, in his comments below. If you change the elements of the copy of a list, inside or outside of the function, the original list will certainly be changed. blogrunner’s list (above) doesn’t change because no elements of the original list were changed; a new list was simply created from some of them.

Example: Write a function which replaces the middle element of a list with the list [‘abc’] if the length of the list is odd, and inserts the list [‘abc’] between the two middle elements if the length is even.

def replace_middle(lst):
    if len(lst) % 2 != 0:
        lst[len(lst)//2] = ['abc']
    else:
        lst.insert(len(lst)//2, ['abc'])
   
lst_1 = [4, 8, 15, 16]
lst_2 = [4, 8, 15, 31, 16]

replace_middle(lst_1)
replace_middle(lst_2)

print(lst_1)
print(lst_2)  

# Output:
[4, 8, ['abc'], 15, 16]
[4, 8, ['abc'], 31, 16]

Notice first, that there is no return statement, and, second, that within the function, list methods were used that do not return a new list, but which operate on the list itself.

1 Like
#49

May I take it that this is what your question is referring to?

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

This will have no effect on the original list but is a new list constructed from the original. We can print it or assign it to a variable at the caller.

s = list('abcdefghijklmnopqrstuvwxyz')
list_without_middle = remove_middle(s, 7, 17)
print (list_without_middle)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print (s)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

It is important to note that when we pass a list object to a function, even though it be given a different local name, it is not a copy, but the global list, itself we are acting upon, Any change to the list in the function will be reflected in the global object.

Above we do not manipulate or modify the list in any way. We merely extracted the data points we wanted and returned them as a new object.

1 Like