added comments. revised redundancy at the start. (#21251)

and minor spelling edits
This commit is contained in:
Roppon Picha
2018-11-08 18:53:02 +07:00
committed by nik
parent 1cf700bb84
commit e5fa49eb13

View File

@ -3,16 +3,15 @@ title: Lambda Expressions
---
## Lambda Expressions
Lambda Expressions are ideally used when we have something simple to be done an we are more interested in quickly getting the job done rather than formally naming the function. Lambda expressions also known as anonymous functions.
Lambda Expressions are ideally used when we have something simple to be done an we are more interested in quickly getting the job done rather than formally naming the function. Lambda expressions are a short way to declare small and anonymous functions (it is not necessary to provide a name for lambda functions) in a concise way.
<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/python/lambda-expressions/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
Lambda Expressions in Python are a short way to declare small and anonymous functions (it is not necessary to provide a name for lambda functions). Lambda functions behave just like regular functions declared with the `def` keyword. They come in handy when you want to define a small function in a concise way. They can contain only one expression, so they are not best suited for functions with control-flow statements.
master
Lambda functions can contain only one expression, so they are not best suited for functions with control-flow statements.
#### Syntax of Lambda Function
`lambda arguments: expression`
Lambda functions can have any number of arguments but only one expression
Lambda functions can have any number of arguments but only one expression.
#### Example code
```py
@ -38,14 +37,14 @@ lambda_func(3) # Returns 9
```
### Intermediate
```py
lambda_func = lambda x: True if x**2 >= 10 else False
lambda_func(3) # Returns False
lambda_func(4) # Returns True
lambda_func = lambda x: True if x**2 >= 10 else False # Function that returns True if the square of x >= 10
lambda_func(3) # Returns False (3**2 = 9, which is < 10)
lambda_func(4) # Returns True (4**2 = 16, which is >= 10)
```
### Complex
```py
my_dict = {"A": 1, "B": 2, "C": 3}
sorted(my_dict, key=lambda x: my_dict[x]%3) # Returns ['C', 'A', 'B']
sorted(my_dict, key=lambda x: my_dict[x]%3) # Returns ['C', 'A', 'B'] # sort dict by the values % 3 (remainders from division by 3)
```
### Use-case
@ -63,7 +62,7 @@ print(filtered) # Python 2: print filtered
# [1, 3, 5, 7, 9]
```
You could write this as a one liner with list-comprehensions
You could write this as a one-liner with list-comprehensions
```python
filtered = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 != 0]