Removing incomplete numbers from list Python

Viewed 47

I'm given this list

[1.3, 2.2, 2.3, 4.2, 5.1, 3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1]

and I'm supposed to remove the elements 1,3, 4.2 and 1.1 so that it becomes

[2.2, 2.3, 5.1, 3.2, 5.3, 3.3, 2.1, 5.2, 3.1]

I have written this code and it becomes wrong. What am I doing wrong?


def removeIncomplete(id):
    numbers_buf = id
    idComplete = id[:]
    for ind, item in enumerate(id):
        if item == 1.3 and item == 4.2 and item == 1.1:
            numbers_buf.remove(item)
        
        return numbers_buf       
        #return idComplete

import numpy as np
print(removeIncomplete(np.array([1.3, 2.2, 2.3, 4.2, 5.1,
3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1])))

#Correct output [ 2.2 2.3 5.1 3.2 5.3 3.3 2.1 5.2 3.1]

2 Answers
def removeIncomplete(id):
    numbers_buf = id
    idComplete = id[:]
    for ind, item in enumerate(id):
        if item == 1.3 or item == 4.2 or item == 1.1:
            numbers_buf = np.delete(numbers_buf, np.where(numbers_buf == item))  
            
    return numbers_buf       
        #return idComplete

import numpy as np
print(removeIncomplete(np.array([1.3, 2.2, 2.3, 4.2, 5.1,
3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1])))

what about using list comprehension

data = [1.3, 2.2, 2.3, 4.2, 5.1, 3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1]
exclude = [1.3, 4.2, 1.1]

out = [val for val in data if val not in exclude]
print(out)
>>>
[2.2, 2.3, 5.1, 3.2, 5.3, 3.3, 2.1, 5.2, 3.1]
Related