# Advanced Python Code Challenges: Lists

remove middle

I tried with this code :

``````> #Write your function here
> def remove_middle(lst, start, end):
>     i=0
>     n=end+1
>     while i<=n:
>       del lst[start+i]
>       i=i+1
>     return lst
>
> #Uncomment the line below when your function is done
> print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
``````

But it returns me with an error :

Traceback (most recent call last):
File â€śscript.pyâ€ť, line 11, in
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
File â€śscript.pyâ€ť, line 6, in remove_middle
del lst[start+i]
IndexError: list assignment index out of range

I dont understand why, can someone explain me.

Then the first step would be to gain insight to the why:

``````while i<=n:
print(i, n, lst)
``````

Well it gives me this :

``````0 4 [4, 8, 15, 16, 23, 42]
1 4 [4, 8, 15, 16, 23, 42]
2 4 [4, 8, 15, 16, 23, 42]
3 4 [4, 8, 15, 16, 23, 42]
4 4 [4, 8, 15, 16, 23, 42]
[4, 8, 15, 16, 23, 42]
``````

which seems logical to me

Edit :

I did some test in Python Shell, and the line del lst[start+i] works like a charm when i is define and lst is not empty, so I dont understand why it doesnt work in a program.

If youâ€™re going to use `del` it might be simpler just to use a slice rather than a loop.

``````>>> a = [4, 8, 15, 16, 23, 42]
>>> del a[1:4]
>>> a
[4, 23, 42]
>>>
``````

Ok thanks, but why my method doesnâ€™t work, when it does in Shell.

``````lst=[4, 8, 15, 16, 23, 42]
i=1
start=1
del lst[start+i]
lst
[4, 8, 16, 23, 42]
``````

Bear in mind that the list is shifting left with each deletion.

Thanks a lot, now I understand my error, I was moving too far in the list, and at one point there was no element anymore, I was out of the list

I change my code to this :

``````def remove_middle(lst, start, end):
i=0
for i in range(0,end-1):
del lst[start+1]
return lst
``````

And it works like a charm, thanks a lot.

1 Like