Created
May 1, 2022 01:56
-
-
Save bennett39/e9df580dd847fb43efc8867b32393ecb to your computer and use it in GitHub Desktop.
This file contains 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, and reduce are all operations that we can apply against a list, tuple, or sequence | |
# These types of operations follow the "functional" approach to programming | |
# I won't go into too much detail here, but a Google search of "functional vs OOP" will give you a synopsis | |
# Here are some examples. We can talk more about them when we chat. | |
# Let's start with a simple list... | |
>>> my_list = [0, 1, 2, 3, 4, 5] | |
# Using filter, we can filter values out of the list, returning a new list! | |
# (If you haven't seen lambdas yet, don't worry! Basically, this filter uses modulo 2 to check if the number is even/odd) | |
>>> filtered = filter(lambda x: x % 2, my_list) | |
>>> [x for x in filtered] | |
[1, 3, 5] | |
# Using map, we also get a new list. This time, runs a function for every value in the list to get a new "mapped" value | |
# The lambda here multiplies each value in the list times two | |
>>> mapped = map(lambda x: x * 2, my_list) | |
>>> [x for x in mapped] | |
[0, 2, 4, 6, 8, 10] | |
# Using reduce, we can "reduce" an entire list down to a single value | |
# Here, the lambda just does a simple sum for every value in the list | |
>>> from functools import reduce | |
>>> reduced = reduce(lambda a, b: a+b, my_list) | |
>>> reduced | |
15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment