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]

HighAllegiant
  • 61
  • 3
  • 9
  • 1
    http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list – Chad Nov 18 '11 at 02: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. – Avaris Nov 18 '11 at 02:00
  • the reason i called my function "filter" was at the request of the instructor in this assignment – HighAllegiant Nov 18 '11 at 02:06
  • Does this answer your question? [Remove all occurrences of a value from a list?](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) – Georgy Feb 19 '20 at 15:21

4 Answers4

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

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • +1. I'd only add that it's good not to use `filter` as a name, since it's already a built-in. – Michael Hoffman Nov 18 '11 at 02:01
  • Thanks for the answers. And the reason I called my function "filter" was at the request of my instructor in this assignment. – HighAllegiant Nov 18 '11 at 02:08
  • 2
    HighAllegiant : In those cases, **please** add the Homework tag to your question. Giving the answer to you in absolutely unhelpful. – Vincent Savard Nov 18 '11 at 02:38
  • 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. :( – Karl Knechtel Nov 18 '11 at 03:51
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))
Community
  • 1
  • 1
0

Custom filter function in python:

def myfilter(fun, data):
    return [i for i in data if fun(i)]
Biman Pal
  • 391
  • 4
  • 9
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]
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485