Reputation: 13
Could you, please, help me to understand why to use filter() instead of def-function in Python? Except it is more readable.
Thank you.
For example,
this one def-function:
def do_even_check(num):
for i in num:
if i % 2 ==0:
print(i)
else:
pass
my_list = [1,2,3,4,5,6,7,8,9,10]
do_even_check(my_list)
And this one with filter()
and lambda
:
filter(lambda num: num % 2 == 0, my_lst)
Upvotes: 1
Views: 92
Reputation: 1987
I advocate that filter, map and reduce (as well as list comprehension) are useful since they often leads to less code lines, which makes your code more maintainable. They are adopted from the functional paradigme where some of the languages advocates type safety. Although python is not a type safe language, it can create predictability by using these functions (filter, map, reduce) or even any build in functions over your own defs as you then will know their return value (a list of items or a single value) and potentially they are known by other developers in your team as well and may be better documented, while your defs may be void (no returned values like your print function), return apples or a string or anything.
Upvotes: 0
Reputation: 6641
The filter
option is better because the result may be re-used, instead your do_even_check(num):
function always prints the output, hindering its re-use in other parts of the program.
Anyway the best way to accomplish this task is neither of your two possibilities but the generator expression:
evens = (i for i in my_list if i % 2 == 0)
As it is the most readable yet concise of all.
Upvotes: 2