A Lambda function is a small, anonymous, and single-line function used to define small and simple operations where writing a full function using 'def' is unnecessary.
Syntax: lambda arguments: experssion
It can take multiple arguments but only one experssion.
Example
add = lambda a, b: a+b
print(add(3, 5))
Normal Function
def add(a, b):
return a + b
Using with one argument
square = lambda a: a*a
print(square(5))
Using with multiple argument
multiply = lambda a, b, c: a * b * c
print(multiply(2, 4, 6))Lambda with map() function
It is use to iterate with every item.
sqr_num = [2, 3, 4, 5]
square = list(map(lambda a: a**2, sqr_num))
print(square)Lambda with filter() function
It is use to filter accroding to condition.
This is a very useful function to sort values.
pair = [("vicky", 1), ("sonal", 2), ("ramesh", 3), ("rani", 4)]
new_sort = list(sorted(pair, key=lambda x: x[0]))
print(new_sort)
Note: x[0] sorts by the first element, while x[1] sorts by the second element. Use reverse=True for descending order. ("vicky", 1): vicky: first element and 1: second element.Practice
Task 1: Sort Even number using Lambda
Task 2: Print Cubes of each number
Task 3: Sorted Number from 1 to 10 from scramble list.
Conclusion
We have complete the Lambda function. It is all about on practic try above code and practice each one and understand the logic behind this.
Practice Your Code Below
🐍 Python Playground
