Python Lesson 117 – Lambda Functions | Dataplexa

Lambda Functions in Python

In this lesson you will learn about Lambda Functions — a short, compact way to write a function in a single line. Lambdas are used everywhere in professional Python — especially when sorting, filtering, and transforming data. By the end of this lesson you will know exactly when and how to use them.


1. What is a Lambda Function?

A lambda function is a small, anonymous function written in one line. Anonymous means it has no name — it is usually created for a short, one-time job and does not need a full def block.

Think of it like a sticky note. A full def function is like a printed instruction manual — detailed, named, saved for repeated use. A lambda is a sticky note — quick, short, written for one specific task right now.

The syntax is:

lambda parameters : expression

There is no def, no function name, no return keyword — the expression is automatically returned. Everything fits on one line.

Where are lambdas used in real life?

  • Sorting a list of dictionaries by a specific field
  • Filtering a list to keep only items that meet a condition
  • Transforming every item in a list with a short calculation
  • Passing a quick function as an argument to another function

2. Lambda vs Regular Function — Side by Side

The best way to understand a lambda is to compare it with a regular def function doing the exact same job. Both produce identical results — the lambda is just more compact.

# Regular function — adds two numbers
def add(a, b):
    return a + b
print(add(10, 5))
# Lambda function — exact same job in one line
add_lambda = lambda a, b : a + b
print(add_lambda(10, 5))
# Regular function — squares a number
def square(n):
    return n * n
print(square(6))
# Lambda — same thing
square_lambda = lambda n : n * n
print(square_lambda(6))
15
15
36
36

What just happened?

  • Both versions produce identical output — the lambda is simply a shorter way to write the same logic.
  • lambda a, b : a + ba and b are the parameters, and a + b is the expression that gets returned automatically.
  • Notice there is no return keyword in a lambda — whatever is after the colon is the return value.

3. Lambda with One Parameter

Lambda functions work with any number of parameters — including just one. These are very common when you need a quick transformation on a single value.

# Convert celsius to fahrenheit
to_fahrenheit = lambda c : (c * 9/5) + 32
print(to_fahrenheit(0))     # freezing point
print(to_fahrenheit(100))   # boiling point
print(to_fahrenheit(37))    # body temperature
# Check if a number is even — returns True or False
is_even = lambda n : n % 2 == 0
print(is_even(4))
print(is_even(7))
# Make a string uppercase with exclamation
shout = lambda text : text.upper() + "!"
print(shout("hello"))
print(shout("welcome to python"))
32.0
212.0
98.6
True
False
HELLO!
WELCOME TO PYTHON!

What just happened?

  • Each lambda has one parameter and one expression — simple, focused, readable.
  • is_even returns a boolean — the expression n % 2 == 0 evaluates to True or False and that is automatically returned.
  • shout chains two string operations in one expression — lambdas can use any valid Python expression after the colon.

4. Lambda with map()

map() applies a function to every item in a list and returns the transformed results. When combined with a lambda, it becomes one of the most powerful one-liners in Python. Instead of writing a loop to transform each item, you do it in a single line.

prices = [100, 250, 80, 500, 175]
# Apply 10% discount to every price using map() + lambda
# map(function, list) — applies the function to each item
discounted = list(map(lambda p : p * 0.9, prices))
print("Original  :", prices)
print("Discounted:", discounted)
# Convert a list of celsius temps to fahrenheit
temps_c = [0, 20, 37, 100]
temps_f = list(map(lambda c : (c * 9/5) + 32, temps_c))
print("Celsius   :", temps_c)
print("Fahrenheit:", temps_f)
Original : [100, 250, 80, 500, 175]
Discounted: [90.0, 225.0, 72.0, 450.0, 157.5]
Celsius : [0, 20, 37, 100]
Fahrenheit: [32.0, 68.0, 98.6, 212.0]

What just happened?

  • map(lambda p : p * 0.9, prices) applies the lambda to every item in prices — each price gets multiplied by 0.9 (10% off).
  • map() returns a map object, so we wrap it in list() to get a regular list back.
  • Without lambda + map, you would need a full loop with a new list and an append — this approach is cleaner and faster to write.

5. Lambda with filter()

filter() keeps only the items from a list where the function returns True. Combined with a lambda, you can filter any list in one clean line — no loop, no temporary list, no appending.

numbers = [3, 18, 7, 42, 5, 30, 11, 60]
# Keep only even numbers
evens = list(filter(lambda n : n % 2 == 0, numbers))
print("Even numbers:", evens)
# Keep only numbers greater than 15
big = list(filter(lambda n : n > 15, numbers))
print("Greater than 15:", big)
# Filter a list of names — keep only names longer than 4 characters
names = ["Jo", "Priya", "Kim", "Arjun", "Lee", "Sneha"]
long_names = list(filter(lambda name : len(name) > 4, names))
print("Long names:", long_names)
Even numbers: [18, 42, 30, 60]
Greater than 15: [18, 42, 30, 60]
Long names: ['Priya', 'Arjun', 'Sneha']

What just happened?

  • filter() runs the lambda on every item and keeps only those where the result is True.
  • lambda n : n % 2 == 0 returns True for even numbers — so only even numbers pass the filter.
  • lambda name : len(name) > 4 checks the length of each name — only names with more than 4 characters are kept.

6. Lambda with sorted() — Sorting Custom Data

This is one of the most common real-world uses of lambdas. The sorted() function has a key parameter where you pass a function — that function decides what value to sort by. A lambda makes this perfectly clean.

# A list of products — each is a tuple: (name, price)
products = [
    ("Keyboard", 1200),
    ("Mouse",     599),
    ("Monitor",  8500),
    ("Webcam",   2200),
    ("Headset",  1800)
]
# Sort by price (index 1) — lowest first
by_price = sorted(products, key=lambda item : item[1])
print("Sorted by price (low to high):")
for name, price in by_price:
    print(f"  {name:<12} ₹{price}")
# Sort by price — highest first (reverse=True)
by_price_desc = sorted(products, key=lambda item : item[1], reverse=True)
print("Sorted by price (high to low):")
for name, price in by_price_desc:
    print(f"  {name:<12} ₹{price}")
Sorted by price (low to high):
  Mouse ₹599
  Keyboard ₹1200
  Headset ₹1800
  Webcam ₹2200
  Monitor ₹8500
Sorted by price (high to low):
  Monitor ₹8500
  Webcam ₹2200
  Headset ₹1800
  Keyboard ₹1200
  Mouse ₹599

What just happened?

  • key=lambda item : item[1] tells sorted() to sort by the second element of each tuple — the price.
  • Without the key parameter, sorted() would sort alphabetically by the first element (name). The lambda gives you full control over what to sort by.
  • reverse=True flips the order from ascending to descending — no extra code needed.

7. Sorting a List of Dictionaries with Lambda

In real programs, data often comes as a list of dictionaries — for example, a list of users or products from a database. Lambda makes it easy to sort this kind of data by any field you choose.

# A list of student dictionaries
students = [
    {"name": "Priya",  "score": 88},
    {"name": "Kiran",  "score": 72},
    {"name": "Arjun",  "score": 95},
    {"name": "Sneha",  "score": 80},
    {"name": "Rahul",  "score": 65}
]
# Sort by score — highest first
ranked = sorted(students, key=lambda s : s["score"], reverse=True)
print("Rank  Name       Score")
print("-" * 25)
for i, student in enumerate(ranked, start=1):
    print(f"  {i}   {student['name']:<10} {student['score']}")
Rank Name Score
-------------------------
  1 Arjun 95
  2 Priya 88
  3 Sneha 80
  4 Kiran 72
  5 Rahul 65

What just happened?

  • key=lambda s : s["score"] tells sorted() to look at the "score" key of each dictionary when deciding the order.
  • This exact pattern is used in every leaderboard, ranking table, and data report in real web applications.
  • enumerate(ranked, start=1) gives each student a rank number starting from 1 — clean and readable.

8. Lambda with a Conditional Expression

A lambda can include a conditional expression (also called a ternary expression) — a one-line if/else. The format is: value_if_true if condition else value_if_false. This lets you add simple logic inside a lambda without breaking the one-line rule.

# Label a number as "Even" or "Odd"
label = lambda n : "Even" if n % 2 == 0 else "Odd"
print(label(4))
print(label(7))
# Assign a pass/fail label based on score
result = lambda score : "Pass" if score >= 50 else "Fail"
print(result(75))
print(result(40))
# Apply a different discount based on quantity
discount = lambda qty : 20 if qty >= 10 else 10
print("Discount for qty 15:", discount(15), "%")
print("Discount for qty 3 :", discount(3),  "%")
Even
Odd
Pass
Fail
Discount for qty 15: 20 %
Discount for qty 3 : 10 %

What just happened?

  • lambda n : "Even" if n % 2 == 0 else "Odd" — if the condition is true, "Even" is returned; otherwise "Odd" is returned.
  • This is the same as writing a full if/else block inside a def function — just compressed into one expression.
  • Keep lambda conditionals simple — if the logic gets complex, switch to a regular def function for better readability.

9. When to Use Lambda vs When to Use def

Lambdas are powerful but they are not always the right choice. Here is a clear guide on when to use each one.

# USE LAMBDA when:
# 1. The function is short — one expression
# 2. It is used as an argument to another function (map, filter, sorted)
# 3. You do not need to reuse it by name
nums = [5, 2, 8, 1, 9]
nums.sort(key=lambda n : n)     # lambda used inline — perfect use case
print("Sorted:", nums)
# USE DEF when:
# 1. The function has multiple lines of logic
# 2. You need to call it by name in many places
# 3. It needs a docstring or clear documentation
def calculate_bmi(weight_kg, height_m):
    """Calculates Body Mass Index."""
    bmi = weight_kg / (height_m ** 2)
    if bmi < 18.5:
        return bmi, "Underweight"
    elif bmi < 25:
        return bmi, "Normal"
    else:
        return bmi, "Overweight"
bmi, label = calculate_bmi(70, 1.75)
print(f"BMI: {bmi:.1f} — {label}")
Sorted: [1, 2, 5, 8, 9]
BMI: 22.9 — Normal

What just happened?

  • The sort with a lambda is a clean, one-line use — it does not need a name or a docstring.
  • The BMI function has multiple lines, returns two values, and has a docstring — a regular def is clearly the better choice here.
  • A good rule of thumb: if you cannot read the lambda out loud in one natural sentence, use a def instead.

10. Real-World Example — Process a Product List

This example puts together map(), filter(), and sorted() with lambdas to process a real product list — the kind of task you would do when building an e-commerce backend or a data processing script.

products = [
    {"name": "Pen",      "price": 15,   "stock": 200},
    {"name": "Notebook", "price": 120,  "stock": 0  },
    {"name": "Bag",      "price": 850,  "stock": 45 },
    {"name": "Ruler",    "price": 25,   "stock": 0  },
    {"name": "Laptop",   "price": 75000,"stock": 10 }
]
# Step 1 — filter: keep only products that are in stock
in_stock = list(filter(lambda p : p["stock"] > 0, products))
# Step 2 — map: add a "discounted_price" key (10% off) to each product
with_discount = list(map(
    lambda p : {**p, "discounted_price": p["price"] * 0.9},
    in_stock
))
# Step 3 — sort: by discounted price, lowest first
final = sorted(with_discount, key=lambda p : p["discounted_price"])
# Display the result
print(f"{'Name':<12} {'Original':>10} {'Discounted':>12}")
print("-" * 36)
for p in final:
    print(f"{p['name']:<12} {p['price']:>10} {p['discounted_price']:>12.2f}")
Name Original Discounted
------------------------------------
Pen 15 13.50
Bag 850 765.00
Laptop 75000 67500.00

What just happened?

  • Step 1 — filter: removed Notebook and Ruler because their stock is 0. Only 3 products remain.
  • Step 2 — map: {**p, "discounted_price": ...} copies all existing keys from the product dictionary and adds a new discounted_price key. **p is the dictionary unpacking syntax.
  • Step 3 — sort: orders the remaining products by discounted price from lowest to highest.
  • This three-step pipeline — filter → transform → sort — is used constantly in data processing, APIs, and backend development.

11. Lesson Summary

Concept Syntax / Example What It Does
Basic lambda lambda x : x * 2 One-line anonymous function
Two parameters lambda a, b : a + b Accepts multiple inputs
With map() map(lambda x : x*2, list) Transforms every item in a list
With filter() filter(lambda x : x>5, list) Keeps only items where result is True
With sorted() sorted(list, key=lambda x : x[1]) Sorts by a custom field
Conditional lambda lambda x : "Yes" if x>0 else "No" Inline if/else inside a lambda
Assign to variable f = lambda x : x + 1 Gives the lambda a name to reuse
Use def instead Multiple lines, reused often When logic is too complex for one line

🧪 Practice Questions

Answer based on what you learned in this lesson.

1. What keyword is used to create a lambda function?




2. Which built-in function applies a lambda to every item in a list?




3. Which built-in function keeps only items from a list where the lambda returns True?




4. When using sorted() with a lambda, which parameter do you pass the lambda to?




5. What does (lambda a, b : a * b)(5, 5) return?



🎯 Quiz — Test Your Understanding

Q1. What does "anonymous" mean when describing a lambda function?







Q2. What does list(map(lambda x : x * 2, [1, 2, 3])) return?







Q3. What does list(filter(lambda x : x % 2 == 0, [1, 2, 3, 4, 5])) return?







Q4. Why does a lambda not need a return keyword?







Q5. When should you use a regular def function instead of a lambda?