⚡ Python Lambda Functions — Small, Fast, Anonymous Functions
Introduction 🌟
A lambda function in Python is a small, anonymous (nameless) function defined using the lambda keyword. Lambdas are used when a simple function is needed for a short period of time.
Note
💡 Lambda functions can contain **only one expression**, not multiple statements.
1. Basic Lambda Function 🧱
basic_lambda.py
square = lambda x: x * x
print(square(5)) # 25✔️ Equivalent to:
regular_function.py
def square(x):
return x * x2. Lambda with Multiple Arguments ➕
multiple_args_lambda.py
add = lambda a, b: a + b
print(add(10, 20))3. Lambda Without Arguments 🔹
no_args_lambda.py
greet = lambda: "Hello!"
print(greet())4. Lambda Inside Functions 🧩
lambda_inside_function.py
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
print(double(5))5. Using Lambda with map() 🗺️
lambda_map.py
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)Note
✔️ map() applies the lambda to each item.
6. Using Lambda with filter() 🔍
lambda_filter.py
nums = [10, 15, 20, 25, 30]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)Note
✔️ filter() keeps only values where lambda returns True.
7. Using Lambda with reduce() ➗
reduce() is in the functools module.
lambda_reduce.py
from functools import reduce
nums = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, nums)
print(total)8. Using Lambda with sorted() 🧮
lambda_sorted.py
students = [("Sathish", 25), ("Kumar", 22), ("Arun", 28)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)Note
✔️ Sorts by age (index 1).
9. Lambda in List Comprehension 🎯
lambda_list_comprehension.py
nums = [1, 2, 3, 4]
res = [(lambda x: x * 2)(n) for n in nums]
print(res)10. Lambda for Conditional Expressions 🔀
lambda_conditional.py
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(5))11. Real-World Uses 🌍
Sorting Dictionaries
lambda_sort_dict.py
employees = [
{"name": "A", "salary": 30000},
{"name": "B", "salary": 50000},
{"name": "C", "salary": 40000},
]
sorted_employees = sorted(employees, key=lambda e: e["salary"])
print(sorted_employees)Extracting Specific Fields
lambda_extract.py
names = list(map(lambda x: x["name"], employees))
print(names)Custom Sorting
lambda_custom_sort.py
words = ["apple", "banana", "kiwi"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)12. When NOT to Use Lambda ⚠️
- When the logic is long — use normal functions for readability.
- When multiple statements are needed — lambda supports only expressions.
- If function needs documentation or clarity — use def.
Conclusion 🎉
>>“Lambda functions are small but mighty — perfect for short, quick operations.” ✨
You now have a clear understanding of lambda functions in Python! Want the next topic? Try Recursion, Modules, Classes & Objects (OOP), or Decorators. Just tell me! 😊