Lists : 13. Removing in Place

Screen Link:

My Code:

def remove_at_idx(lst, ind):
    lst = lst[:ind] + lst[ind+1:]

What I expected to happen:
When I execute the above code with some test inputs, I am getting the desired result. That is the list is updated by removing the element mentioned at the given index. But when I click the submit button I am getting the below error.

I checked the solution provided by DQ where pop() method is used. But I would like to know what is the issue with my code.

What actually happened:

Paste output/error here

1 Like

After your function, use the sample code on the page and copy it into your window before running it:

a_list = ["A", "B", "C", "D", "E"]
remove_at_idx(a_list, 3)

This is the test you want to use to see if the function will pass the challenge.

I found an article about lists you might like to look through. It might help you with seeing the difference. The 2 key ideas you can take away from it are:

  1. Non-in-place methods don’t alter their object; instead, they return a copy of that object

  2. We can use the plus sign operator to concatenate two lists, in the same way we can use it to concatenate two string objects. The result of the concatenation […] is an entirely new object

I hope that helps.


Thank you for the explanation. I understand now, here we had to update the list with ‘inplace’ concept and hence this code fails.
I executed the code with the below test values and it was working fine and hence had this doubt.

Code :
def remove_at_idx(lst, ind):
    return  lst[:ind] + lst[ind+1:]

Test case:
a_list = ["A", "B", "C", "D", "E"]
print(remove_at_idx(a_list, 3))

["A", "B", "C", "E"]
1 Like

I also need to update the list with ‘inplace’ concept.
Thanks for sharing the article and highlighting the 2 key ideas.