map filter reduce python code example
Example 1: python filter
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
Example 2: python map reduce
mylist = [5, 4, 6, "other random stuff", True, "22", "map", False, ""]
def multiply_by_two(obj):
return obj*2
def is_str(obj):
return type(obj) == str
list(map(multiply_by_two, mylist))
# [10, 8, 12, "other random stuffother random stuff", 2, "2222", "mapmap", 0, ""]
list(filter(is_str, mylist))
# ["other random stuff", "22", "map", ""]
# You could also use lambdas on both examples:
list(map(lambda x: x*2, mylist))
list(filter(lambda x: type(x) == str, mylist))