Skip to content

Instantly share code, notes, and snippets.

@StuffbyYuki
Last active November 26, 2020 17:35
Show Gist options
  • Save StuffbyYuki/5397cb67831f0b2ea66334970426a039 to your computer and use it in GitHub Desktop.
Save StuffbyYuki/5397cb67831f0b2ea66334970426a039 to your computer and use it in GitHub Desktop.
Python: map(), filter(), reduce() functions
# map(), filter(), reduce() apply a function to every element in what you pass in
def add(a):
return a + 10
arr = [1,2,3]
print(map(add, arr)) # returns 11, 12, 13
def gt_two(a):
return a > 2
print(filter(gt_two, arr)) # returns [3]
from functools import reduce
def multiply(a, b):
return a * b
print(reduce(multiply, arr)) # returns 6 - multiply every element in arr
print(reduce(multiply, arr, 2)) # return 12 - with an initial value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment