0

I am using the filter function for the first time and using a function to remove del_num from a tuple called num_list. However, it's not doing what I want. I am getting back the original num_list values. Appreciate any ideas on how to get this to work.

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list, del_num):
    new_num =[]
    for v in num_list:
        if (num_list) == (del_num):
            return FALSE
        else:
            new_num.append(v)
    return new_num

result = filter_list(num_list,del_num)
print(result)

3 Answers 3

1

Making minimal changes to the overall structure of your code, but making some changes so it works:

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list, del_num):
    new_num = []
    for v in num_list:
        if v != del_num:
            new_num.append(v)
    return new_num

result = filter_list(num_list,del_num)
print(result)

The return False portion of your code will break out of the function and return False if the condition is met, which is not what you want. Additionally, the equality check you were doing was comparing the original list to the number to be deleted. You should have done if v == del_num. Given that all the action happens in the else block, easiest to turn the equality into an inequality and get rid of the else block entirely.

Also note that the boolean False is spelt False, not FALSE (unlike some other languages).

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. What does v! do? Assuming one can change the tuple to a list and get this to also work.
!= is the inequality operator - the opposite of ==. v != del_num is asking whether an individual list item is NOT EQUAL to del_num. I'm not sure what you mean about changing the tuple - there aren't any tuples in the code.
Clarifying my question. If i change the input values to strings, will this function initialize. I tried it and it doesnt work.
The function should still work, but may not do what you intend: filter_list('aabcda', 'a') returns ['b', 'c', 'd'].
1

One way to do this is using list comprehension

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list,del_num):
    return [num for num in num_list if num != del_num]

filtered_list = filter_list(num_list,del_num)
print(filtered_list)

Comments

0

Here is what are you looking for:

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list, del_num):

 new_num =[]

for v in num_list:
    if (v) == (del_num):
        pass
    else:
        new_num.append(v)
return new_num

result = filter_list(num_list,del_num)

print(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.