|
| 1 | +🔓**Lambda Function Cheatsheet**: |
| 2 | + |
| 3 | +Lambda functions in Python serve as concise and disposable snippets of code, akin to the fast food of programming—swift and convenient, yet not always the most maintainable choice. These functions are particularly valuable in Competitive Programming scenarios where time and code length are limited, allowing for quick implementation of specific functionalities with minimal overhead. |
| 4 | +Here's its features and a quick shortcuts to get you up to speed with lambda functions: |
| 5 | + |
| 6 | +1. **Basic Syntax**: Lambda functions are defined using the `lambda` keyword, followed by parameters/arguments and a colon, and then the expression you want to evaluate. |
| 7 | + |
| 8 | + Syntax: |
| 9 | + ```python |
| 10 | + lambda arguments: expression |
| 11 | + ``` |
| 12 | + Example: |
| 13 | + ```python |
| 14 | + add = lambda x, y: x + y |
| 15 | + ``` |
| 16 | + Equivalent with: |
| 17 | + ```python |
| 18 | + def add(x, y): |
| 19 | + return x + y |
| 20 | + ``` |
| 21 | + |
| 22 | +3. **Single Expression Only**: Lambda functions can only contain a single expression. |
| 23 | + |
| 24 | + Example: |
| 25 | + ```python |
| 26 | + # This lambda function adds 10 to the input number |
| 27 | + add_ten = lambda x: x + 10 |
| 28 | + ``` |
| 29 | + |
| 30 | +4. **No Statements**: Lambda functions cannot contain statements, only expressions. |
| 31 | + |
| 32 | + Example: |
| 33 | + ```python |
| 34 | + # Incorrect: Lambda functions cannot contain statements like print, because it's assigning obtained value to vaiable. |
| 35 | + greet = lambda name: print(f"Hello, {name}!") |
| 36 | + ``` |
| 37 | + |
| 38 | +5. **Anonymous Functions**: Lambda functions are anonymous, meaning they don't have a name. |
| 39 | + |
| 40 | + Example: |
| 41 | + ```python |
| 42 | + # Anonymous lambda function to check if a number is even |
| 43 | + is_even = lambda x: x % 2 == 0 |
| 44 | + ``` |
| 45 | + |
| 46 | +6. **Use Cases**: Lambda functions are handy for short, one-off functions, especially when used with functions like `map()`, `filter()`, and `sorted()`. |
| 47 | + |
| 48 | + Example: |
| 49 | + ```python |
| 50 | + # Using lambda with filter to get even numbers from a list |
| 51 | + numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 52 | + even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) |
| 53 | + ``` |
| 54 | + |
| 55 | +Remember, while lambda functions can be useful, they're not always the best choice, especially when working with Projects. |
| 56 | +Sometimes, writing out a full function definition can make your code more readable and maintainable. |
| 57 | +So, use lambda functions wisely, like a spicy condiment—not too much, just enough to add some flavor to your code. 🌶️ |
0 commit comments