Last active
November 26, 2020 17:35
-
-
Save StuffbyYuki/5397cb67831f0b2ea66334970426a039 to your computer and use it in GitHub Desktop.
Python: map(), filter(), reduce() functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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