Function remove_at_idx did not return the expected value, but the output is correct

In the exercise, I got the correct output, but rejected answer ( I’ve checked other topics, but couldn’t find any reason that leads to my mistake). My code:

list_1 = ["A", "B", "C", "D", "E"]

list_2 = ["A", "A", "A"]
list_3 = [0, 1, 2, 2, 2, 2, 1]


def remove_at_idx(list_x, number):
    for string in range(len(list_x)):
        if string == number and number >= 0:
            list_x.remove(list_x[string])
    return list_x
        
        
print(remove_at_idx(list_1, 0))
print(remove_at_idx(list_2, 1))            
print(remove_at_idx(list_3, 1))    

What’s interesting, when I changed the remove() method into the pop() method, the answer was granted.
Why?

code accepted below:

list_1 = ["A", "B", "C", "D", "E"]

list_2 = ["A", "A", "A"]
list_3 = [0, 1, 2, 2, 2, 2, 1]


# def remove_at_idx(list_x, number):
#     for string in range(len(list_x)):
#         if string == number and number >= 0:
#             list_x.remove(list_x[string])
#     return list_x

def remove_at_idx(list_x, number):
    for string in range(len(list_x)):
        if string == number and number >= 0:
            list_x.pop(string)
    return list_x


        
print(remove_at_idx(list_1, 0))
print(remove_at_idx(list_2, 1))            
print(remove_at_idx(list_3, 1))    

Hi @drill_n_bass,

The issue here is with different functionality of remove() and pop(). The first method removes from the list the first value that matches the one in the parenthesis, and not the one at some specific index. The pop() method, instead, removes the value from the list at a specific index.

To check it, just modify your list_2 in the following way:

list_2 = ["A", "B", "B", "A"]

modify also the print statement for it, to remove the value at the index [3]:

print(remove_at_idx(list_2, 3)) 

and use your function with remove().
You’ll see that this function will remove the first “A”, at the index [0], and not the one at the specified index [3].

1 Like

Hello @drill_n_bass,

Sometimes, python docs will have a concise explanation.


Try this by varying the parameters:

test_string = ["A", "B", "C", "D", "E", "E"]
idx = 3

def remove_at_idx(string, idx, char):
    
    # .pop(3) will pop-out the element at position/index 3
    if idx <= len(string):
        string.pop(idx)
        
    # .remove("E") will remove the first occurrence of "E" if it exists in the string
    if char in string:
        string.remove(char)

    print(string)


remove_at_idx(test_string, idx, "E")
1 Like

thank You Elena_Kosourova and veena.sanjeeve.line. Now I understand the difference very well. :slight_smile:

2 Likes