How to make a filter/remove like function to remove instances of an integer in a list by using a reduce function only in python
Question:
Hey I am pretty new to python and self learning it for me to eventually be somewhat decent in my coding skill i have got an idea of using map/filter/reduce functions. I am trying a challenge friend gave me to remove and element from list using remove filter and reduce
here is my code for filter
def removeall_ft(item, test_list):
res = list(filter(lambda x: x!=item, test_list))
return res
print(removeall_ft(0, [1,0,1]))
it gives [1,1]
working great
import functools
def removeall_rd(item, test_list):
res = functools.reduce(lambda x,y: x if y!=item else x, test_list)
return res
print(removeall_ft(0, [1,0,1]))
but this doesnt give me desired answer any help is appreciated
Answers:
functools.reduce returns a new(or mutated) object
def reduce_step(return_so_far,this_value):
if this_value !=item:
return [*return_so_far,this_value]
return return_so_far
it takes a method to reduce, a target list, and an optional initial_value for the result (return_so_far
)
item = 4
result = reduce(reduce_step,[1,2,3,4,5,6,7],[])
print(result)
as mentioned in the comments this is not a very good way to filter a list
Hey I am pretty new to python and self learning it for me to eventually be somewhat decent in my coding skill i have got an idea of using map/filter/reduce functions. I am trying a challenge friend gave me to remove and element from list using remove filter and reduce
here is my code for filter
def removeall_ft(item, test_list):
res = list(filter(lambda x: x!=item, test_list))
return res
print(removeall_ft(0, [1,0,1]))
it gives [1,1]
working great
import functools
def removeall_rd(item, test_list):
res = functools.reduce(lambda x,y: x if y!=item else x, test_list)
return res
print(removeall_ft(0, [1,0,1]))
but this doesnt give me desired answer any help is appreciated
functools.reduce returns a new(or mutated) object
def reduce_step(return_so_far,this_value):
if this_value !=item:
return [*return_so_far,this_value]
return return_so_far
it takes a method to reduce, a target list, and an optional initial_value for the result (return_so_far
)
item = 4
result = reduce(reduce_step,[1,2,3,4,5,6,7],[])
print(result)
as mentioned in the comments this is not a very good way to filter a list