Home > Software engineering >  Why is remove() only removing the first element from the list in Python?
Why is remove() only removing the first element from the list in Python?

Time:12-29

So, I working on a problem where there is a list lt=[1, 1, 3, 4, 5, 5] and k =1.So, I am trying to remove all the occurrences of k from the list and return the list but when I use the in built method remove() it only deletes the first occurrence while ignoring the the other occurrences. The output I receive is [1,3,4,5,5] and output I expect is [3,4,5,5] Below is my code , thank you.

class Solution(object):

    def remove_occurances(self, lt, k):

        i = 0
        while i < len(sorted(lt)):
            if lt[i] == k:
                lt.remove(lt[i])
                i  = 1
            return lt


if __name__ == "__main__":
    p = [1, 1, 3, 4, 5, 5]
    k = 1
    print(Solution().remove_occurances(p, k))

CodePudding user response:

Within remove_occurances you could instead have:

def remove_occurances(self, lt, k):
    while k in lt:
        lt.remove(k)

    return lt

Note that this function is working directly on the input list, so the remove calls will alter that input list. Also the returned list lt will be the same list (i.e., a pointer to the same memory rather than a copy) as this input list lt.

If you want the original input list to be unaltered, you'd need to do something like:

def remove_occurances(self, lt, k):
    newlist = list(lt)  # make a copy of lt
    while k in newlist:
        newlist.remove(k)  # remove from the copy

    return newlist  # return the copy

This will keep looping while the list lt still contains the value k.

CodePudding user response:

You are returning too quickly:

def remove_occurances(self, lt, k):

    i = 0
    while i < len(sorted(lt)):
        if lt[i] == k:
            lt.remove(lt[i])
        else:
            i  = 1
    
    return lt

Outputs:

[3, 4, 5, 5]

CodePudding user response:

You should remove in loop.

Not to remove from a specific location, but to remove a specific value, as long as it exists in the list.

When there is no more of this array - it will raise a valueEttor, and you will know that all the requested values have been removed.

   try:
        while True:
            lt.remove(k)
    except ValueError:
        pass

EDIT: to measure time:

    from time import time

    start_time = time()

    try:
        while True:
            lt.remove(k)
    except ValueError:
        pass

    end_time = time()
     
        
    print("TOTAL TIME: "   str(end_time-start_time))

CodePudding user response:

p = [1, 1, 3, 4, 5, 5]
k = 1
def remove_occurances(p, k):
    return [i for i in p if i != k] # here we are using list comprehension and taking only values expect the value to be removed.
remove_occurances(p, k)
#[3, 4, 5, 5]
  • Related