Last active
September 13, 2021 22:20
-
-
Save elowy01/1b275d06f0b58d9db6246f5d3c721e91 to your computer and use it in GitHub Desktop.
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
| #### Lambdas | |
| In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. | |
| is a function without a name (you can also call it an anonymous function) | |
| # An example is a square function: | |
| # this is equivalent | |
| def square(num): | |
| return num * num | |
| # to the lambda | |
| square_lambda = lambda num : num * num | |
| # this is called like this: | |
| assert square(3) == square_lambda(3) | |
| two = lambda: 2 | |
| sqr = lambda x: x * x | |
| pwr = lambda x, y: x ** y | |
| for a in range(-2, 3): | |
| print(sqr(a), end=" ") | |
| print(pwr(a, two())) | |
| ##### | |
| # Processing a collection with 'map': | |
| # Let's assume we have a list of integers and we want to get another list | |
| # where all the elements are multiplied by 2. We can use the 'map' function | |
| # for this: | |
| domain = [1, 2, 3, 4, 5] | |
| our_range = map(lambda num: num * 2, domain) | |
| print(list(our_range)) # we need to convert to list here, as map returns a | |
| # a map object | |
| # this will return: | |
| [2, 4, 6, 8, 10] | |
| ## | |
| # Processing a collection with 'filter': | |
| domain = [1, 2, 3, 4, 5] | |
| our_range = map(lambda num: num * 2, domain) | |
| print(list(our_range)) | |
| evens = filter(lambda num: num % 2 == 0, domain) | |
| print(list(evens)) | |
| # If we run this (we get the evens): | |
| [2, 4, 6, 8, 10] | |
| [2, 4] | |
| # Sort using the key parameter. It takes a function that each item in the | |
| # collection will be processed with before the comparison is run to determine | |
| # the order. | |
| # For example: | |
| words = ['Boss', 'a', 'Alfred', 'fig', 'Daemon', 'dig'] | |
| print("Sorting by default") | |
| print(sorted(words)) | |
| # we get: | |
| ['Alfred', 'Boss', 'Daemon', 'a', 'dig', 'fig'] | |
| print("Sorting with a lambda key") | |
| print(sorted(words, key=lambda s: s.lower())) | |
| # we get: | |
| ['a', 'Alfred', 'Boss', 'Daemon', 'dig', 'fig'] | |
| #### | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment