agyanadda@gmail.com

Python Lambda, map, filter and sorted

Functions and Modules 1 min read Updated Dec 4, 2026 Topic 18 of 32

A lambda is a small, one-line, unnamed function:

lambda arguments: expression

square = lambda x: x * x is the same as def square(x): return x * x.

Lambdas can only contain one expression — no statements, loops or return.

Where lambdas shine

As short functions passed to other functions:

  • sorted(students, key=lambda s: s["marks"]) — sort by a field
  • max(products, key=lambda p: p["price"])
  • map(lambda x: x * 2, nums) — apply to every item
  • filter(lambda x: x > 0, nums) — keep matching items

map and filter return iterators — wrap with list() to see the results.

Comprehension or map/filter?

[x * 2 for x in nums] is often clearer than map. Use whichever is more readable.

Avoid

Assigning lambdas to names for real functions — use def so the function has a proper name in error messages.

Example

Example — Sorting and filtering products Python
products = [
    {"name": "Laptop", "price": 54999, "rating": 4.5},
    {"name": "Mouse", "price": 499, "rating": 4.1},
    {"name": "Keyboard", "price": 1299, "rating": 4.7},
]

cheapest_first = sorted(products, key=lambda p: p["price"])
print([p["name"] for p in cheapest_first])

best = max(products, key=lambda p: p["rating"])
print("Best rated:", best["name"])

affordable = list(filter(lambda p: p["price"] < 2000, products))
print("Under 2000:", [p["name"] for p in affordable])

with_gst = list(map(lambda p: round(p["price"] * 1.18), products))
print(with_gst)

Output: ['Mouse', 'Keyboard', 'Laptop'], Best rated: Keyboard, Under 2000: ['Mouse', 'Keyboard'], [64899, 589, 1533]

Test Yourself With Exercises

Exercise 1 Multiple Choice

What can a lambda body contain?

Exercise 2 True / False

map() returns an iterator, so you often wrap it in list().

Exercise 3 Fill in the Blank

Sort by price: sorted(items, ___=lambda x: x["price"])

Frequently Asked Questions

Only when the function is short and used once, usually as a key or callback. If it has a meaningful name or is reused, write a normal def function.