Day 15/100: Lambda Functions β Python’s Anonymous One-Liners
Welcome to Day 15 of the 100 Days of Python series!
Today, we explore lambda functions β short, simple, and anonymous functions that fit in one line of code. They’re great for quick calculations, especially when paired with functions like map(), filter(), and sorted().
Letβs break it down with examples and real-world use cases.
π¦ What Youβll Learn
- What a lambda function is
- Syntax of a lambda
- How it’s different from
def - Real-world use cases
- Common mistakes to avoid
π§ What Is a Lambda Function?
A lambda function is a small anonymous function (no name). It’s often used when you need a quick function for a short task.
πΉ Syntax:
lambda arguments: expression
It can have any number of arguments, but only one expression.
π§ Example 1: Basic Lambda Function
square = lambda x: x * x
print(square(5)) # Output: 25
This is equivalent to:
def square(x):
return x * x
π― Example 2: Multiple Arguments
add = lambda a, b: a + b
print(add(3, 7)) # Output: 10
βοΈ Common Use: Inside map(), filter(), sorted()
Using with map()
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16]
Using with filter()
nums = [5, 12, 17, 18, 24, 3]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [12, 18, 24]
Using with sorted() (custom key)
students = [("John", 88), ("Alice", 92), ("Bob", 75)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print(sorted_students)
# [('Alice', 92), ('John', 88), ('Bob', 75)]
π§ͺ Real-World Example: Tip Calculator
calculate_tip = lambda bill, percent: round(bill * percent / 100, 2)
print(calculate_tip(200, 10)) # Output: 20.0
π€ When to Use Lambda Functions
β Use lambdas when:
- You need a short function for a quick task
- You donβt want to define a full function using
def - Youβre using functions like
map(),filter(),sorted()
π« Avoid lambdas when:
- The logic is complex
- You need multiple lines
- You need reusability or debugging support
β οΈ Common Mistakes
- Trying to write multiple lines: Lambdas only support single expressions
- Overusing lambdas: Makes code harder to read and maintain
- Using lambdas when
defis more appropriate
π lambda vs def
| Feature | lambda |
def |
|---|---|---|
| Name | Anonymous | Named |
| Length | One-line | Multi-line |
| Reusability | Not reusable (typically) | Reusable |
| Best for | Quick, short logic | Full function logic |
π§ Recap
Today you learned:
- What lambda functions are and how to write them
- The syntax:
lambda args: expression - How to use them with
map(),filter(), andsorted() - When and when not to use lambdas
- Real-world examples like tip calculators and sorting