2

I'm trying to create a function:

filter(delete,lst) 

When someone inputs:

filter(1,[1,2,1]) 

returns [2]

What I have come up with was to use the list.remove function but it only deletes the first instance of delete.

def filter(delete, lst):

"""

Removes the value or string of delete from the list lst

"""

   list(lst)

   lst.remove(delete)

   print lst

My result:

filter(1,[1,2,1])

returns [2,1]

4
  • 1
    stackoverflow.com/questions/1157106/… Commented Nov 18, 2011 at 2:00
  • 1
    I'd suggest choosing a different name for your function. There is a built-in filter function and you'll be masking it. Commented Nov 18, 2011 at 2:00
  • the reason i called my function "filter" was at the request of the instructor in this assignment Commented Nov 18, 2011 at 2:06
  • Does this answer your question? Remove all occurrences of a value from a list? Commented Feb 19, 2020 at 15:21

4 Answers 4

8

Try with list comprehensions:

def filt(delete, lst):
    return [x for x in lst if x != delete]

Or alternatively, with the built-in filter function:

def filt(delete, lst):
    return filter(lambda x: x != delete, lst)

And it's better not to use the name filter for your function, since that's the same name as the built-in function used above

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

4 Comments

+1. I'd only add that it's good not to use filter as a name, since it's already a built-in.
Thanks for the answers. And the reason I called my function "filter" was at the request of my instructor in this assignment.
HighAllegiant : In those cases, please add the Homework tag to your question. Giving the answer to you in absolutely unhelpful.
Between this and your other question, it looks to me like your instructor is hell-bent on making people do easy problems the hard way for no reason. :(
0

I like the answer from Óscar López but you should also learn to use the existing Python filter function:

>>> def myfilter(tgt, seq):
        return filter(lambda x: x!=tgt, seq)

>>> myfilter(1, [1,2,1])
[2]

Comments

0

Custom Filter Function

def my_filter(func,sequence):
    res=[]
    for variable in sequence :
        if func(variable):
            res.append(variable)
    return res

def is_even(item):
    if item%2==0 :
        return True
    else :
        return False
 
    

seq=[1,2,3,4,5,6,7,8,9,10]
print(my_filter(is_even,seq))

1 Comment

Output will be [2, 4, 6, 8, 10].Here the address of is_even and func is same.
0

Custom filter function in python:

def myfilter(fun, data):
    return [i for i in data if fun(i)]

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.