SyntaxPilot
Courses/Python/Lesson 17

Python · Lesson 17 of 40 · 12 min

Lambda, map, filter, sorted

queued

These are the notes for Python episode 17. The problem sounds simple: rank the class by marks. It pushes us to hand a function to another function (the key= argument), and then to invent a function so small it fits inside one line: the lambda. You will learn why sorted() can't compare dictionaries, the key= function, passing a function vs calling it, lambda, reverse=True, max() and min() with a key, breaking ties with a tuple key, why list.sort() returns None, map() and filter() (and why they print <map object>), and when a comprehension (episode 16) is clearer. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

The problem: rank the class

The class register: Ravi 72, Asha 35, Meera 90. The teacher wants a rank list. You learned sorted() in episode 10, so the first attempt keeps names and marks in two lists and sorts each one:

names = ["Ravi", "Asha", "Meera"]
marks = [72, 35, 90]

print(sorted(names))
print(sorted(marks))

Output:

['Asha', 'Meera', 'Ravi']
[35, 72, 90]

Names alphabetical, marks low to high. But who scored 90? The two lists were sorted separately, so the link between a name and its marks is gone.

So keep each student together, as a dictionary, and sort the list of dictionaries:

students = [
    {"name": "Ravi", "marks": 72},
    {"name": "Asha", "marks": 35},
    {"name": "Meera", "marks": 90},
]

print(sorted(students))

Output:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(sorted(students))
          ~~~~~~^^^^^^^^^^
TypeError: '<' not supported between instances of 'dict' and 'dict'

Why: to sort, Python repeatedly compares two items: "is this one smaller (<) than that one?" It knows how for numbers (72 < 90) and strings (alphabetical). For two dictionaries it has no idea which field you care about: the name or the marks? So it refuses.

The same happens with mixed types:

print(sorted([10, "9", 8]))

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(sorted([10, "9", 8]))
          ~~~~~~^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'str' and 'int'

The key= function

Think of the PT teacher at morning assembly:

On the school ground In Python
Students in a line, each a whole person students, a list of dicts (whole records)
"Line up by height": look at one thing per student key=by_marks, a function: student → marks
Shortest to tallest; the whole student moves sorted(students, key=...): whole dicts, in marks order

The rule is a function. You pass it as key, and sorted() calls it on every item to get the value to compare.

students = [
    {"name": "Ravi", "marks": 72},
    {"name": "Asha", "marks": 35},
    {"name": "Meera", "marks": 90},
]

def by_marks(s):
    return s["marks"]

for s in sorted(students, key=by_marks):
    print(s["name"], s["marks"])

Output:

Asha 35
Ravi 72
Meera 90

Behind the scenes, sorted() called by_marks() on each student, got 72, 35 and 90, sorted by those numbers, and moved the whole dictionaries.

Passing a function vs calling it

A very common mistake is writing brackets after the function name:

students = [
    {"name": "Ravi", "marks": 72},
    {"name": "Asha", "marks": 35},
    {"name": "Meera", "marks": 90},
]

def by_marks(s):
    return s["marks"]

print(sorted(students, key=by_marks()))

Output:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    print(sorted(students, key=by_marks()))
                               ~~~~~~~~^^
TypeError: by_marks() missing 1 required positional argument: 's'

by_marks() calls the function right now, with no student. key needs the function itself, by_marks without brackets, so that sorted() can call it later, once per item. In Python, functions are values: you can store them in variables and pass them to other functions, just like numbers or lists.

lambda: a one-line function with no name

by_marks works, but it's a whole def, with a name, for a function we use exactly once. Python has a shortcut:

lambda inputs: expression
  • lambda: the keyword that starts a nameless function.
  • inputs: its parameters, like the ones in def f(inputs).
  • expression: the value it returns (no return keyword).

lambda s: s["marks"] is exactly the same as def by_marks(s): return s["marks"].

students = [
    {"name": "Ravi", "marks": 72},
    {"name": "Asha", "marks": 35},
    {"name": "Meera", "marks": 90},
]

for s in sorted(students, key=lambda s: s["marks"], reverse=True):
    print(s["name"], s["marks"])

top = max(students, key=lambda s: s["marks"])
print("Topper:", top["name"])

Output:

Meera 90
Ravi 72
Asha 35
Topper: Meera
  • reverse=True sorts from biggest to smallest.
  • max() and min() take a key too. min(students, key=lambda s: s["marks"]) gives Asha.

A lambda is a normal function value; you can even store it in a variable (though for anything reused, a def with a good name is clearer):

double = lambda x: x * 2
print(double(21))
add = lambda a, b: a + b
print(add(3, 4))

print(sorted(["banana", "kiwi", "apple"], key=len))

print(sorted(["banana", "Kiwi", "apple"]))
print(sorted(["banana", "Kiwi", "apple"], key=str.lower))

Output:

42
7
['kiwi', 'apple', 'banana']
['Kiwi', 'apple', 'banana']
['apple', 'banana', 'Kiwi']
  • Built-in functions work as keys: key=len sorts by length.
  • Capital letters sort before small ones (all capitals come before all small letters in the character table), so "Kiwi" comes first. key=str.lower compares everything in small letters.
  • key=abs sorts numbers by size, ignoring the sign: sorted([3, -7, 2, -1], key=abs) → [-1, 2, 3, -7].

Numbers typed as text

Prices typed by a user arrive as strings. Sorting them gives a surprise:

prices = ["10", "9", "2", "100"]

print(sorted(prices))
print(sorted(prices, key=int))

Output:

['10', '100', '2', '9']
['2', '9', '10', '100']

Strings are compared character by character, like words in a dictionary: "1" comes before "2", so "10" and "100" go first. key=int compares each string as a number, but the original strings come back. The key changes how items are compared, never the items themselves.

What sorted() does with a key, step by step

  1. It calls the key function once on every item: Ravi → 72, Asha → 35, Meera → 90.
  2. It sorts using only those values: 35, 72, 90.
  3. It returns the whole items in that order.

Because sorted() does the calling, you give it the function's name, never a call with brackets.

What a lambda can't do

A lambda holds exactly one expression. No return, no loops, no assignments:

square = lambda x: return x * x

Output:

  File "main.py", line 1
    square = lambda x: return x * x
                       ^^^^^^
SyntaxError: invalid syntax

The lambda already returns its expression: write lambda x: x * x. If you need more than one line, write a normal def.

Breaking ties: a tuple key

Cricket scores. Rohit and Gill both made 45. Highest runs first, and for a tie, alphabetical:

players = [("Rohit", 45), ("Virat", 82), ("Gill", 45), ("Rahul", 12)]

print(sorted(players, key=lambda p: (-p[1], p[0])))

Output:

[('Virat', 82), ('Gill', 45), ('Rohit', 45), ('Rahul', 12)]
  • The key returns a tuple: (-runs, name). Tuples are compared item by item: the second item only matters when the first ones are equal.
  • The minus sign flips a number so that the highest comes first, while the name stays A to Z. (reverse=True would flip both.)
  • Python's sort is stable: items with equal keys keep their original order. That's why sorting words by their last letter keeps samosa before dosa.

Sorting a dictionary

Marks stored as a dictionary, name → marks. sorted() on a dictionary sorts its keys only:

scores = {"Ravi": 72, "Asha": 35, "Meera": 90, "Kabir": 81}

print(sorted(scores))

ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(ranked)
for name, marks in ranked:
    print(name, marks)

print("Topper:", max(scores, key=scores.get))

Output:

['Asha', 'Kabir', 'Meera', 'Ravi']
[('Meera', 90), ('Kabir', 81), ('Ravi', 72), ('Asha', 35)]
Meera 90
Kabir 81
Ravi 72
Asha 35
Topper: Meera
  • scores.items() gives (name, marks) pairs; kv[1] (index 1) is the marks.
  • scores.get is a function that takes a key and returns its value, so it works as a key too: max(scores, key=scores.get) gives the name with the highest marks. Again, no brackets after get.
  • To turn the ranked pairs back into a dictionary (which keeps insertion order): dict(ranked).

sort() vs sorted()

names = ["Ravi", "Asha", "Meera"]

result = names.sort()
print(result)
print(names)

Output:

None
['Asha', 'Meera', 'Ravi']
sorted(x) x.sort()
What it is a built-in function a list method
Works on any iterable (list, tuple, string, set, dict keys) lists only
The original left unchanged changed in place
Returns a new sorted list None
key=, reverse= yes yes

Storing the result of .sort() is a classic bug:

names = ["Ravi", "Asha"]
names = names.sort()
print(names[0])

Output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(names[0])
          ~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

map() and filter()

A bottling factory:

In the factory In Python
Every bottle passes the same machine and gets a cap map(f, items): f applied to every item
Quality check: broken bottles are removed filter(f, items): keeps the items where f returns True
Nothing is done until the truck comes both are lazy: wrap them in list() to get the results
line = "10 20 30"
parts = line.split()
print(parts)

nums = map(int, parts)
print(nums)

nums = list(map(int, parts))
print(nums, sum(nums))

Output (the address differs on each run):

['10', '20', '30']
<map object at 0x7f2fcf09ac20>
[10, 20, 30] 60

map() returns a map object: a lazy recipe (like the generator in episode 16) that does the work only when someone asks for the values. list() asks for all of them. list(map(int, input().split())) is how competitive programmers read a line of numbers.

A lazy object can be used only once:

nums = map(int, ["1", "2", "3"])
print(sum(nums))
print(sum(nums))

Output:

6
0

The second sum() finds the map already used up. Store list(map(...)) if you need the values twice.

map/filter vs comprehensions

marks = [35, 72, 48, 90, 38]

print(list(filter(lambda m: m >= 40, marks)))
print([m for m in marks if m >= 40])

print(list(map(lambda m: m + 5, marks)))
print([m + 5 for m in marks])

Output:

[72, 48, 90]
[72, 48, 90]
[40, 77, 53, 95, 43]
[40, 77, 53, 95, 43]

Identical results. Most Python programmers find the comprehension easier to read. Use map when you already have a named function (map(int, parts), map(str.upper, names)), and a comprehension when you'd need a lambda. Combining both gets hard to read fast:

print(list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, range(7)))))

Output:

[0, 4, 16, 36]

The comprehension [x * x for x in range(7) if x % 2 == 0] says the same thing more clearly.

Common mistakes

Mistake What you see Why Fix
sorted(students) on a list of dicts TypeError: '<' not supported between instances of 'dict' and 'dict' Python doesn't know what to compare key=lambda s: s["marks"]
sorted([10, "9", 8]) TypeError: '<' not supported between instances of 'str' and 'int' numbers and strings can't be compared convert first: key=int
key=by_marks() TypeError: by_marks() missing 1 required positional argument: 's' the brackets call it too early key=by_marks
result = names.sort() no error, result is None .sort() changes the list in place names.sort() alone, or sorted(names)
names = names.sort() then names[0] TypeError: 'NoneType' object is not subscriptable names is now None don't assign .sort()'s result
print(map(int, parts)) <map object at 0x...> map is lazy list(map(int, parts))
using a map/filter object twice the second use is empty (0, []) lazy objects are used up store list(...)
lambda x: return x * x SyntaxError: invalid syntax a lambda is one expression lambda x: x * x
["banana", "Kiwi", "apple"] sorted Kiwi comes first capitals sort before small letters key=str.lower
sorted(["10", "9", "2", "100"]) ['10', '100', '2', '9'] strings compare character by character key=int
sorted(scores) on a dict, expecting a ranking only the keys, alphabetical sorting a dict sorts its keys sorted(scores.items(), key=lambda kv: kv[1])

Mini project: sort restaurants like a food app

Each restaurant has a name, a rating and a delivery time in minutes. Sort by rating, highest first; when two have the same rating, the faster one comes first. That's a tuple key: (-rating, mins).

# Mini project: sort restaurants like a food app
restaurants = [
    {"name": "Chai Point", "rating": 4.2, "mins": 25},
    {"name": "Dosa Plaza", "rating": 4.5, "mins": 40},
    {"name": "Biryani House", "rating": 4.5, "mins": 30},
    {"name": "Pizza Corner", "rating": 3.9, "mins": 20},
]

best = sorted(restaurants, key=lambda r: (-r["rating"], r["mins"]))
for r in best:
    print(r["rating"], r["mins"], "min", r["name"])

fast = [r["name"] for r in restaurants if r["mins"] <= 25]
print("Under 25 min:", fast)

Output:

4.5 30 min Biryani House
4.5 40 min Dosa Plaza
4.2 25 min Chai Point
3.9 20 min Pizza Corner
Under 25 min: ['Chai Point', 'Pizza Corner']

Biryani House beats Dosa Plaza: same rating, ten minutes faster.

Extend it: add the name as a third tie-breaker (practice 4).

Practice

1. Sort words by their last letter.

Solution
words = ["chai", "samosa", "lassi", "dosa", "idli"]
print(sorted(words, key=lambda w: w[-1]))

Output:

['samosa', 'dosa', 'chai', 'lassi', 'idli']

w[-1] is the last character. Words with the same last letter keep their original order (a stable sort).

2. Sort (name, age) pairs by age, then by name.

Solution
people = [("Ravi", 25), ("Asha", 19), ("Meera", 25), ("Kabir", 19)]
print(sorted(people, key=lambda p: (p[1], p[0])))

Output:

[('Asha', 19), ('Kabir', 19), ('Meera', 25), ('Ravi', 25)]

3. Read "5 3 9 1" and print the largest number, using map.

Solution
line = "5 3 9 1"
nums = list(map(int, line.split()))
print(max(nums))

Output:

9

Without map(int, ...), max() would compare strings, and max(["5", "3", "9", "10"]) is "9", not "10".

4. Food app: the name as a third tie-breaker (two restaurants now tie on rating and time).

Solution
restaurants = [
    {"name": "Chai Point", "rating": 4.2, "mins": 25},
    {"name": "Dosa Plaza", "rating": 4.5, "mins": 30},
    {"name": "Biryani House", "rating": 4.5, "mins": 30},
    {"name": "Pizza Corner", "rating": 3.9, "mins": 20},
]
best = sorted(restaurants, key=lambda r: (-r["rating"], r["mins"], r["name"]))
for r in best:
    print(r["rating"], r["mins"], "min", r["name"])

Output:

4.5 30 min Biryani House
4.5 30 min Dosa Plaza
4.2 25 min Chai Point
3.9 20 min Pizza Corner

5. The student with the lowest marks, the first name alphabetically, and the names sorted longest first, in place.

Solution
students = [{"name": "Ravi", "marks": 72}, {"name": "Asha", "marks": 35}, {"name": "Meera", "marks": 90}]
low = min(students, key=lambda s: s["marks"])
print(low["name"])
print(sorted(students, key=lambda s: s["name"])[0]["name"])
names = ["Ravi", "Asha", "Meera"]
names.sort(key=len, reverse=True)
print(names)

Output:

Asha
Asha
['Meera', 'Ravi', 'Asha']

Ravi and Asha both have 4 letters, so they keep their original order.

Quick quiz

1. The video's quiz:

words = ["pear", "fig", "banana"]
print(sorted(words, key=len, reverse=True))
Answer

['banana', 'pear', 'fig']. The key compares lengths (4, 3, 6), and reverse=True puts the longest first.

2. What does this print?

nums = [3, -7, 2, -1]
print(sorted(nums, key=abs))
Answer

[-1, 2, 3, -7]. abs gives 3, 7, 2, 1, and the numbers are arranged by those values, but the original numbers (with their signs) are what's returned.

3. What's wrong here, and what's printed?

nums = map(int, ["1", "2", "3"])
print(sum(nums))
print(sum(nums))
Answer

6, then 0. The map object is lazy and can be used only once; the second sum() gets nothing.

4. Which is the same as def f(x): return x % 2 == 0? (a) lambda x: return x % 2 == 0 (b) lambda x: x % 2 == 0 (c) lambda: x % 2 == 0

Answer

(b). (a) is a SyntaxError (no return in a lambda); (c) takes no input, so x isn't its parameter.

Interview questions

  1. What is a lambda in Python? An anonymous (nameless) function defined with lambda args: expression. It can hold only a single expression, whose value is returned.
  2. What does the key argument of sorted() do? It's a function called once per item; the items are ordered by the values it returns, while the original items are what end up in the result.
  3. Difference between sort() and sorted()? list.sort() sorts a list in place and returns None; sorted() works on any iterable and returns a new list.
  4. How do you sort by multiple criteria? Return a tuple from the key, e.g. key=lambda s: (-s["marks"], s["name"]); tuples compare item by item.
  5. Is Python's sort stable? Yes (Timsort): items with equal keys keep their relative order. That's what lets you sort in several passes.
  6. What do map() and filter() return in Python 3? Lazy iterators (map and filter objects), not lists; wrap in list() to materialise them. They can be consumed only once.
  7. map/filter or comprehensions? Comprehensions are usually preferred for readability; map is neat with an existing function like int or str.strip.
  8. What is a higher-order function? A function that takes another function as an argument or returns one: sorted, map, filter, max with key.

Glossary

Term Meaning Example
key= A function that turns each item into the value to compare when sorting key=len
Key function The function passed as key by_marks, lambda s: s["marks"]
Lambda A small nameless function: lambda inputs: expression lambda x: x * 2
Anonymous function A function without a name; in Python, a lambda lambda a, b: a + b
Higher-order function A function that takes or returns another function sorted, map, filter
First-class functions Functions are values: stored in variables, passed to other functions key=by_marks
sorted() Returns a new sorted list from any iterable sorted(names)
list.sort() Sorts a list in place and returns None names.sort()
In place Changing the original object instead of making a new one .sort()
reverse=True Sort from biggest to smallest sorted(m, reverse=True)
Stable sort Items with equal keys keep their original order samosa stays before dosa
Tuple key A key that returns a tuple, to sort by several things (-runs, name)
max() / min() with key The item whose key value is largest / smallest max(students, key=...)
map() Applies a function to every item, lazily map(int, parts)
filter() Keeps the items for which a function returns True, lazily filter(lambda m: m >= 40, marks)
Map object / lazy iterator A recipe that produces values only when asked, once <map object at 0x...>
str.lower The string method as a function value, used as a key key=str.lower
abs() The size of a number without its sign abs(-7) → 7
split() Breaks a string into a list of words "10 20".split() → ['10', '20']

Summary

  • sorted() can't compare dictionaries: TypeError: '<' not supported between instances of 'dict' and 'dict'. Tell it what to compare with key=.
  • key takes a function, passed without brackets; sorted() calls it once per item.
  • lambda inputs: expression is a one-line nameless function, perfect for keys. One expression only, no return.
  • reverse=True for biggest first; max() and min() take key too; a tuple key like (-marks, name) breaks ties.
  • Numbers stored as text sort as text: use key=int. A dictionary sorts by keys; rank it with sorted(d.items(), key=lambda kv: kv[1]).
  • list.sort() sorts in place and returns None; sorted() returns a new list.
  • map() applies a function to every item, filter() keeps the items that pass; both are lazy (wrap in list()), and usable once.
  • Prefer a comprehension over map/filter with a lambda.

Next episode: errors and exceptions. Stop red error messages from crashing your programs with try, except, else, finally and raise.