Home > database >  How to delete all elements from a given list in Python?
How to delete all elements from a given list in Python?

Time:04-13

I am receiving an list and a number as input parameters to a method:

def removeElement(nums: list[int], val: int):

I am trying to traverse thru all the elements of nums and remove all of them if they are same.

def removeElement(nums: list[int], val: int):
    for i in nums:
        if i == val:
            nums.remove(i)
    print(nums)
    return nums

When I pass an array: [0, 1, 2, 2, 3, 0, 4, 2] and input val: 2, I still last number 2 of the list in the output. output: [0, 1, 3, 0, 4, 2] enter image description here

Note: I shouldn't be using extra list or any other collection for space complexity. Could anyone let me know what is the mistake I am making here and how can I correct it ?

CodePudding user response:

for i in nums creates an iterator, which isn't modified for subsequent iterations. You can simply use a while loop with the del function to remove all target values.

def removeElement(nums, val):
    i = 0
    while i<len(nums):
        if nums[i] == val:
            del nums[i]
        else:
            i  = 1
    print(nums)
    return nums

removeElement([0, 1, 2, 2, 3, 0, 4, 2, 2], 2) #[0, 1, 3, 0, 4]

CodePudding user response:

The issue is that when doing for i in nums:, i gets assigned to first element of nums, then 2nd etc, even if some elements are removed, that means in your case after removing the first 2 at 3rd position it moves to 4th position which is now a 3, so it skips the originally 4th 2.

To fix it you could count the number of occurrences of val and remove them afterwards accordingly :

def removeElement(nums: list[int], val: int):
    cnt = 0
    for i in nums:
        if i == val:
            cnt  = 1
    for _ in range(cnt):
        nums.remove(val)
    print(nums)
return nums

CodePudding user response:

You are removing elements from the same list you are looping. This causes loop to end before it reaches the last element.

You can loop the array in reverse order and remove elements using index.

def removeElement(nums, val):
    for i in range(len(nums) - 1, -1, -1):
        if nums[i] == val:
            del nums[i]
    return nums

CodePudding user response:

You can use this:

def removeElement(nums, val):
    while val in nums:
        nums.remove(val)
    print(nums)
    return nums

This removes every val in nums

PS: This code is short and readable, but on large lists pretty slow.

  • Related