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

Removing the multiples of a number in a list

So I wanted to delete the multiples of a number (in this case 2) inside a list. My code basically works put for some reason the number 6 doesn’t get removed any idea how I can fix this?

Input:

def remove_multiples(l, n):
    i = 0
    while i < len(l):
        element = l[i]
        if element % n == 0:
            l.remove(element)
        i += 1
    return l

l = [3,5,2,6,8,9]
print(remove_multiples(l, 2))

Output:

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

[3, 5, 6, 9]

>Solution :

I added a print statement to the remove_multiples function to see how the loop is behaving. I think it might be useful to understand what is happening following your approach

def remove_multiples(lst, num):
    i = 0
    while i < len(lst):
        # let's add a print to check how the loop is behaving
        print(f"indexing elem {i}: value{l[i]}")
        if l[i] % num == 0:
            # we remove the item. even if we do not update i, due to the removal of the lst item, when the next iteration starts i will access the next element 
            l.pop(i)
        else:
            # we continue
            i += 1
    return lst

# or using list comphrension
def remove_multiples_v2(lst, num):
    [i for i in lst if i % num != 0]


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