Module 6 · Beginner · Functions and modules

Python lambda, map, filter and sorted with key

Python lambda functions with map, filter and sorted: sorting with key by marks or length, max with key, reduce, and when a comprehension is clearer.

By theprogrammers team · · 9 min read

You have a list of students with their marks and need it sorted from highest to lowest mark. sorted(students) doesn't know what "by marks" means. You have to tell it, by handing it a small function that picks out the marks from each student. Writing a full def for a one-line job feels heavy, so Python lets you write it inline: key=lambda s: s["marks"]. Python lambda functions with map, filter and sorted are all about passing small functions into other functions.

This is the first time many learners treat a function as a value, something you can store in a variable or pass around like a number. Once that idea clicks, sorting by any rule, picking the maximum by any measure and transforming whole lists all become one-liners.

What you need first: Python functions and Python comprehensions.

Key terms

  • First-class function: in Python, functions are values. You can store them in variables, put them in lists and pass them to other functions.
  • Lambda: a small function with no name, written in one expression: lambda x: x * 2.
  • Key function: a function you pass to sorted, max, min and others, which tells them what to compare.
  • map: applies a function to every item of an iterable.
  • filter: keeps only the items for which a function returns True.
  • Higher-order function: a function that takes a function as an argument, or returns one.

Functions are values

Before lambda, see that a function's name is just a variable that holds a function:

def shout(text):
    return text.upper() + "!"

speak = shout                 # no brackets: we're not calling it
print(speak("hello"))

def apply_twice(func, value):
    return func(func(value))

print(apply_twice(shout, "hi"))
HELLO!
HI!!

Without brackets, shout is the function itself. With brackets, shout("hello") calls it. apply_twice is a higher-order function: it takes another function and uses it.

How to write a lambda in Python

A lambda is a short way to write a function that returns one expression:

lambda parameters: expression

These two do exactly the same thing:

def add_gst(price):
    return price * 1.18

add_gst_lambda = lambda price: price * 1.18

print(round(add_gst(500), 2), round(add_gst_lambda(500), 2))
590.0 590.0

Rules for lambdas:

  • Only one expression. No if blocks, loops or several statements. A conditional expression is fine: lambda m: "Pass" if m >= 40 else "Fail".
  • No return keyword: the expression's value is returned automatically.
  • Any number of parameters: lambda a, b: a + b.

Assigning a lambda to a name, as above, is legal but pointless: use def, which gives the function a proper name in error messages. PEP 8, Python's style guide, says the same. Lambdas are for passing straight into another function, which is the rest of this lesson.

sorted with key

sorted() returns a new sorted list. Its key argument is a function that turns each item into the value to compare:

words = ["banana", "Kiwi", "apple", "fig"]

print(sorted(words))
print(sorted(words, key=len))
print(sorted(words, key=str.lower))
print(sorted(words, key=len, reverse=True))
['Kiwi', 'apple', 'banana', 'fig']
['fig', 'Kiwi', 'apple', 'banana']
['apple', 'banana', 'fig', 'Kiwi']
['banana', 'apple', 'Kiwi', 'fig']

Plain sorted puts "Kiwi" first because capital letters come before lower-case ones in Unicode. key=str.lower compares the lower-case versions instead. Built-in functions like len and str.lower work as keys directly; you only need a lambda when there's no ready-made function.

Sorting records with a lambda

students = [
    {"name": "Ahana", "marks": 88, "age": 20},
    {"name": "Rohan", "marks": 72, "age": 19},
    {"name": "Meera", "marks": 95, "age": 21},
    {"name": "Kabir", "marks": 88, "age": 19},
]

by_marks = sorted(students, key=lambda s: s["marks"], reverse=True)
print([s["name"] for s in by_marks])
['Meera', 'Ahana', 'Kabir', 'Rohan']

Ahana and Kabir both have 88. Python's sort is stable: items that compare equal keep their original order, so Ahana stays before Kabir.

Sorting by two things

Return a tuple from the key. Python compares tuples item by item, so the second value breaks ties:

students = [
    {"name": "Ahana", "marks": 88, "age": 20},
    {"name": "Rohan", "marks": 72, "age": 19},
    {"name": "Meera", "marks": 95, "age": 21},
    {"name": "Kabir", "marks": 88, "age": 19},
]

ranked = sorted(students, key=lambda s: (-s["marks"], s["name"]))
print([(s["name"], s["marks"]) for s in ranked])
[('Meera', 95), ('Ahana', 88), ('Kabir', 88), ('Rohan', 72)]

-s["marks"] sorts marks from high to low while names still go A to Z. The minus trick only works on numbers.

sort() vs sorted()

list.sort() sorts the list in place and returns None. sorted() works on any iterable and returns a new list. Both accept key and reverse.

marks = [72, 95, 64]
result = marks.sort()
print(result, marks)
None [64, 72, 95]

Writing marks = marks.sort() is a common mistake that replaces your list with None.

max and min with key

max and min take a key too, and return the whole item, not just the value compared:

cities = [("Delhi", 41), ("Shimla", 24), ("Jaipur", 44)]
print(max(cities, key=lambda c: c[1]))
print(min(cities, key=lambda c: c[1]))

prices = {"tea": 20, "coffee": 40, "samosa": 15}
print(max(prices, key=prices.get))
('Jaipur', 44)
('Shimla', 24)
coffee

max(prices, key=prices.get) is a neat trick: it loops over the keys and compares them by their values, giving the key with the highest value.

map: apply a function to every item

map(function, iterable) calls the function on each item. It returns a map object, which gives its results one at a time; wrap it in list() to see them all:

prices = [100, 250, 499]
print(list(map(lambda p: round(p * 1.18, 2), prices)))

print(list(map(int, ["10", "20", "30"])))
print(list(map(str.title, ["ahana", "rohan"])))
[118.0, 295.0, 588.82]
[10, 20, 30]
['Ahana', 'Rohan']

map(int, input().split()), which you may have seen for reading numbers, is exactly this.

map can take several iterables, and passes one item from each:

quantities = [2, 1, 3]
unit_prices = [40, 120, 15]
print(list(map(lambda q, p: q * p, quantities, unit_prices)))
[80, 120, 45]

filter: keep only some items

filter(function, iterable) keeps the items for which the function returns True:

marks = [35, 82, 47, 91, 28, 66]
print(list(filter(lambda m: m >= 40, marks)))

names = ["Ahana", "", "Rohan", "", "Meera"]
print(list(filter(None, names)))
[82, 47, 91, 66]
['Ahana', 'Rohan', 'Meera']

filter(None, ...) keeps only the "truthy" items, which removes empty strings, zeros and None.

map and filter, or comprehensions?

The same jobs as comprehensions:

marks = [35, 82, 47, 91, 28, 66]

print(list(map(lambda m: m + 5, filter(lambda m: m >= 40, marks))))
print([m + 5 for m in marks if m >= 40])
[87, 52, 96, 71]
[87, 52, 96, 71]

The comprehension is easier to read, and most Python developers prefer it. Our advice: use comprehensions by default, and map when you already have a named function, as in map(int, parts) or map(str.strip, lines). Combining map, filter and lambdas gets hard to read quickly.

reduce: combine everything into one value

functools.reduce applies a two-argument function across a list, carrying the result along: ((a + b) + c) + d.

from functools import reduce

numbers = [2, 3, 4]
print(reduce(lambda total, n: total * n, numbers))
print(reduce(lambda a, b: a if a > b else b, [34, 78, 12, 95, 60]))
24
95

For sums, products and maximums, sum, math.prod and max are clearer. reduce is mostly something to recognise when you see it.

Where this is used

  • pandas: df["price"].apply(lambda p: p * 1.18) and df.sort_values(key=...) use the same idea on whole columns.
  • Sorting in apps: leaderboards, "sort by price" buttons and search results all sort by a key.
  • Data pipelines: map(clean_row, rows) processes rows one at a time without loading everything into memory.
  • GUIs and web frameworks: you pass functions as callbacks, to be called when a button is clicked or a URL is visited.

Common mistakes

  • Calling the function when passing it: sorted(words, key=len()) raises TypeError. Pass len, without brackets.
  • Printing a map object directly: print(map(...)) shows <map object at 0x...>. Wrap it in list().
  • Using a map or filter object twice. They're used up after one pass; the second loop gets nothing.
  • Writing long lambdas. If it doesn't fit comfortably on one line, use def with a clear name.
  • marks = marks.sort(), which sets marks to None.

Practice

  1. Sort ["Pune", "Goa", "Bengaluru", "Delhi"] by length, shortest first.
Show the answer
print(sorted(["Pune", "Goa", "Bengaluru", "Delhi"], key=len))
['Goa', 'Pune', 'Delhi', 'Bengaluru']
  1. Use map to convert temperatures [0, 25, 37.5, 100] from Celsius to Fahrenheit (F = C × 9 ÷ 5 + 32).
Show the answer
celsius = [0, 25, 37.5, 100]
print(list(map(lambda c: c * 9 / 5 + 32, celsius)))
[32.0, 77.0, 99.5, 212.0]
  1. Use filter to keep only the even numbers from 1 to 20 that are also divisible by 3.
Show the answer
print(list(filter(lambda n: n % 2 == 0 and n % 3 == 0, range(1, 21))))
[6, 12, 18]
  1. Sort these products by price from low to high, and by name for equal prices.
products = [("pen", 10), ("notebook", 45), ("eraser", 5), ("ruler", 10)]
Show the answer
products = [("pen", 10), ("notebook", 45), ("eraser", 5), ("ruler", 10)]
print(sorted(products, key=lambda p: (p[1], p[0])))
[('eraser', 5), ('pen', 10), ('ruler', 10), ('notebook', 45)]
  1. Find the word with the most vowels in ["python", "education", "rhythm", "queue"].
Show the answer

The key counts the vowels in each word:

words = ["python", "education", "rhythm", "queue"]
print(max(words, key=lambda w: sum(ch in "aeiou" for ch in w)))
education

"education" has 5 vowels; "queue" has 4.

  1. Rewrite this with a list comprehension: list(map(lambda s: s.strip().lower(), filter(lambda s: s.strip(), raw))), where raw = [" Pune ", "", " GOA", " "].
Show the answer
raw = [" Pune ", "", " GOA", "  "]
print([s.strip().lower() for s in raw if s.strip()])
['pune', 'goa']

Interview questions

What is a lambda function in Python, and what are its limits?

A lambda is an anonymous function defined in a single expression, such as lambda x: x * 2. It can't contain statements like loops, assignments or return, and it has no name in tracebacks, so it's best for short functions passed to sorted, map, filter or similar.

What is the difference between sort() and sorted()?

list.sort() sorts a list in place and returns None. sorted() accepts any iterable and returns a new sorted list, leaving the original unchanged. Both take key and reverse, and both are stable.

What does it mean that Python's sort is stable?

Items that compare equal keep their original relative order. This lets you sort by several keys in passes, or rely on ties staying in their input order.

Key takeaways

  • Functions are values: pass them without brackets, call them with brackets.
  • lambda args: expression makes a small unnamed function; use def for anything longer.
  • sorted, max and min take key=; return a tuple from the key to sort by several things.
  • map transforms every item and filter keeps some; both return one-time iterators.
  • Comprehensions are usually clearer than map and filter with lambdas.

Frequently asked questions

Can a lambda have an if statement?

Not an if block, but it can use a conditional expression: lambda m: "Pass" if m >= 40 else "Fail".

Is map faster than a list comprehension?

With a built-in function like map(int, items), map can be slightly faster. With a lambda, a comprehension is usually as fast or faster. The difference rarely matters; choose what's clearer.

How do I sort a dictionary by its values?

sorted(d.items(), key=lambda kv: kv[1]) gives a list of (key, value) pairs sorted by value. Wrap it in dict(...) to get a dictionary in that order.

What to learn next

  1. Say what types your functions expect with type hints for beginners.
  2. Go back to recursion in Python to see lru_cache, another function that works on functions.
  3. Use key functions in pandas in the pandas DataFrame tutorial.