Some text some message..
Back 12 🧠 What is a Lambda Function? 23 Jun, 2025

A lambda function is a small anonymous function in Python.

It can have any number of arguments, but only one expression.

✅ Syntax:

lambda arguments: expression

🔹 Key Characteristics

Feature Description
Anonymous No need to name the function
Single Expression Must return the result of one expression
Return Value Automatically returns the result
Used With map(), filter(), reduce(), sorted()

🔸 Basic Example

square = lambda x: x * x
print(square(5))  # Output: 25

This is equivalent to:

def square(x):
    return x * x

🔸 Lambda with Multiple Arguments

add = lambda a, b: a + b
print(add(3, 7))   # Output: 10

🔸 Lambda Inside map()

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared)  # Output: [1, 4, 9, 16]

🔸 Lambda Inside filter()

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # Output: [2, 4, 6]

🔸 Lambda Inside sorted() with Custom Key

names = ['Abhi', 'John', 'Zack', 'Mark']
sorted_names = sorted(names, key=lambda x: x[-1])
print(sorted_names)
# Output: ['Zack', 'Mark', 'Abhi', 'John']

🔸 Lambda Inside reduce() (from functools)

from functools import reduce

product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product)  # Output: 24

💡 Best Practices

Do ✅ Don't ❌
Use for simple one-liners Avoid for complex logic
Use with map, filter, sorted Avoid nested lambda functions
Keep it readable and meaningful Don’t overuse; use def if better

❗ When not to use Lambda?

  • When the function logic is complex or multi-line

  • When you need reusability or documentation (docstrings)

  • When you need clarity (named functions are easier to debug)