|
| 1 | +#Python Lambda Functions |
| 2 | +''' |
| 3 | +Lambda Functions in Python are anonymous functions, |
| 4 | +implying they don't have a name. The def keyword is needed to create |
| 5 | +a typical function in Python, as we already know. We can also use |
| 6 | +the "lambda" keyword in Python to define an unnamed function. |
| 7 | +
|
| 8 | +Syntax of Python Lambda Function |
| 9 | +lambda arguments: expression |
| 10 | +''' |
| 11 | +#Example1 |
| 12 | +# Code to demonstrate how we can use a lambda function |
| 13 | +add = lambda num: num + 4 |
| 14 | +print( add(6) ) |
| 15 | +''' |
| 16 | +Output |
| 17 | +10 |
| 18 | +''' |
| 19 | +#Example2 |
| 20 | +def reciprocal( num ): |
| 21 | + return 1 / num |
| 22 | +lambda_reciprocal = lambda num: 1 / num |
| 23 | +print( "Lambda keyword: ", lambda_reciprocal(6) ) |
| 24 | +print( "Def keyword: ", reciprocal(6) ) |
| 25 | +''' |
| 26 | +Output |
| 27 | +Def keyword: 0.16666666666666666 |
| 28 | +Lambda keyword: 0.16666666666666666 |
| 29 | +''' |
| 30 | +#Example3 Lambda Function with filter() |
| 31 | +# Code to filter odd numbers from a given list |
| 32 | +list_ = [34, 12, 64, 55, 75, 13, 63] |
| 33 | +odd_list = list(filter( lambda num: (num % 2 != 0) , list_ )) |
| 34 | +print(odd_list) |
| 35 | +''' |
| 36 | +Output |
| 37 | +[55, 75, 13, 63] |
| 38 | +''' |
| 39 | +#Example4 Lambda Function with map() |
| 40 | +#Code to calculate the square of each number of a list using the map() |
| 41 | +# function |
| 42 | +numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10] |
| 43 | +squared_list = list(map( lambda num: num ** 2 , numbers_list )) |
| 44 | +print( squared_list ) |
| 45 | +''' |
| 46 | +Output |
| 47 | +[4, 16, 25, 1, 9, 49, 64, 81, 100] |
| 48 | +''' |
| 49 | + |
| 50 | +#Example5 Lambda Function with List Comprehension and For Loop |
| 51 | +#Code to calculate square of each number of list using list comprehension |
| 52 | +squares = [lambda num = num: num ** 2 for num in range(0, 11)] |
| 53 | +for square in squares: |
| 54 | + print( square(), end = " ") |
| 55 | +''' |
| 56 | +Output |
| 57 | +0 1 4 9 16 25 36 49 64 81 100 |
| 58 | +''' |
| 59 | + |
| 60 | +#Example6 Lambda Function with if-else |
| 61 | +Minimum = lambda x, y : x if (x < y) else y |
| 62 | +print(Minimum( 35, 74 )) |
| 63 | +''' |
| 64 | +Output |
| 65 | +35 |
| 66 | +''' |
0 commit comments