Python map-reduce-filter
Jump to navigation
Jump to search
Map, Reduce and Filter
- Map: applies a function to each value of an iterable, with basic syntax: map(function, iterable).
def square(x):
return x*x
mynums = [17, 10, 3, 1, 5, 14, 15, 10, 6, 12]
result = map(square, mynums)
# or
result = map(lambda x: x*x, mynums)
# output
list(result)
[289, 100, 9, 1, 25, 196, 225, 100, 36, 144]
- Filter: filters out values from an iterable object(list, tuple, set, etc.)
def less_than_10(x):
if x < 10:
return x
# called function
list(filter(less_than_10, mynums))
# using a lambda function
list(filter(lambda x: x < 10, mynums))
# output
[3, 1, 5, 6]