Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Using enumerate to remove number occurrence not working

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading