-1

the following code is me that wrote it to remove all the val numbers in the list nums. But for some reason I only managed to remove all of them except for the last one. Does anyone know how to remove all of the val numbers inside the list nums

def removeElement(nums,val):
    for i in nums:
        if i == val:
            nums.remove(nums[nums.index(i)])
    return nums
removeElement([3,5,2,637,2,2,73,73,2,5,26,2,62,26,2],2)
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
  • Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Hampus Larsson Aug 22 '21 at 12:43
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Tomerikoo Aug 22 '21 at 13:27
  • `nums[nums.index(i)]` is just a very long and confusing way of saying `i` – Tomerikoo Aug 22 '21 at 13:28

2 Answers2

0

The problem is that the index changes in the loop and it is not that only the last element is not removed, try this:

print(removeElement([2,2,4],2))

output:

[2, 2, 4]

you can use this for this problem:

def removeElement(nums,val):
    nums = [i for i in nums if i not in [val]]
    return nums
print(removeElement([3,5,2,637,2,2,73,73,2,5,26,2,62,26,2],2))

output:

[3, 5, 637, 73, 73, 5, 26, 62, 26]
Salio
  • 1,058
  • 10
  • 21
0

Your function did not delete the last one because your for loop exit before reaching the last element.

Removing an element during loop will make your loop jump before finding the last element because your array have less element than before.

Does anyone know how to remove all of the val numbers inside the list nums

Yes, here is how you can fix your code:

def removeElement(nums, val):
    for n, i in reversed(list(enumerate(nums))):
        if i == val:
            del nums[n]
    return nums

removeElement([3,5,2,637,2,2,73,73,2,5,26,2,62,26,2], 2)

Let me explain my fix. The n is the index of nums array.

Iterating the array in reverse order will ensure that even if you remove an element from it during the loop, the next element to be processed is still there.

Having the n index position, I can simply use del to remove the element at specific index in the array.

apogee
  • 111
  • 3