I am trying to remove every occurrence of a particular number from a list. The code does not remove the number when its twice in a row. i expect it to remove every occurrence of 1. I have no idea why this is happening, maybe i am making a silly mistake.
def rem_num(numbers: list[int], x: int) -> list[int]:
print(list(enumerate(numbers)))
for i,num in enumerate(numbers):
if num == x:
numbers.pop(i)
return numbers
print(rem_num([1,2,3,4,1,1,2,3,4,5,1,1,5],1))
Output:
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 1), (5, 1), (6, 2), (7, 3), (8, 4), (9, 5), (10, 1), (11, 1), (12, 5)]
[2, 3, 4, 1, 2, 3, 4, 5, 1, 5]
>Solution :
The problem is that you remove elements from the list while iterating through it. Your counter does increment one by one, but then you skip elements as your list shortens.
def rem_num(numbers: list[int], x: int) -> list[int]:
print(list(enumerate(numbers)))
for i,num in enumerate(numbers):
if num == x:
numbers.pop(i)
print(i, len(numbers))
return numbers
print(rem_num([1,2,3,4,1,1,2,3,4,5,1,1,5],1))
See the output:
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 1), (5, 1), (6, 2), (7, 3), (8, 4), (9, 5), (10, 1), (11, 1), (12, 5)]
0 12
1 12
2 12
3 11
4 11
5 11
6 11
7 11
8 10
9 10
[2, 3, 4, 1, 2, 3, 4, 5, 1, 5]
For instance, when you have your input list [2,3,4,1,1,2,3,4,5,1,1,5] and the index is, let say, 3, then you’ll remove the first 1 in the list. So the counter i will increment to 4, but the the second 1 will then remain at index 3 so you won’t remove that one.