
๐ Day 95/150 – Lambda Function Examples in Python
A lambda function is a small, anonymous function in Python. It is useful when you need a simple function for a short period without defining it using the def keyword.
The syntax of a lambda function is:
lambda arguments: expressionIn this post, we'll explore four common examples of lambda functions in Python.
Method 1 – Simple Lambda Function
Create a lambda function to add two numbers.
add = lambda a, b: a + b
print(add(5, 3))
Output
8
Explanation
lambda a, b: defines an anonymous function with two parameters.
a + b is the expression whose result is returned automatically.
add(5, 3) returns 8.
Method 2 – Lambda with map()
Use a lambda function with map() to square each element in a list.
[1, 4, 9, 16, 25]numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x ** 2, numbers)) print(squares)
Output
Explanation
map() applies the lambda function to every element in the list.
lambda x: x ** 2 returns the square of each number.
list() converts the result into a list.
Method 3 – Lambda with filter()
Use a lambda function to filter even numbers from a list.
[2, 4, 6]numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
Output
Explanation
filter() keeps only the elements for which the lambda function returns True.
lambda x: x % 2 == 0 checks whether a number is even.
The result is converted into a list.
Method 4 – Lambda with sorted()
Sort a list of tuples based on the second element.
[('Charlie', 78), ('Alice', 85), ('Bob', 92)]students = [ ("Alice", 85), ("Bob", 92), ("Charlie", 78) ] sorted_students = sorted(students, key=lambda student: student[1]) print(sorted_students)
Output
Explanation
sorted() sorts the list.
The key parameter specifies the sorting rule.
lambda student: student[1] tells Python to sort using the second element (marks).
Comparison of Methods
| Method | Best For |
|---|---|
| Simple Lambda | Short mathematical operations |
| map() | Transforming every element |
| filter() | Selecting elements based on a condition |
| sorted() | Custom sorting |
๐ฅ Key Takeaways
A lambda function is a small anonymous function written in a single line.
It is best suited for short and simple operations.
map() uses lambda functions to transform data.
filter() uses lambda functions to select matching elements.
sorted() uses lambda functions to define custom sorting rules.
For complex logic, use a regular function (def) instead of a lambda function.
Stay tuned for Day 96 of the #150DaysOfPython series! ๐

0 Comments:
Post a Comment