Reading history

Python Lambda Functions, map, filter and Sorting with key

5 min read 0 views

Learn Python lambda functions: syntax, lambda vs def, map, filter and reduce, and sorting lists and dictionaries with sorted(key=...), reverse and max/min.

The lambda keyword lets you build a throw-away function on the spot, right inside the line that needs it. It shines when another function asks you for a short rule just once, for example the rule that decides how a list is sorted. This lesson covers lambda syntax, using lambdas with map, filter and reduce, and sorting with the key argument, which is where lambdas appear most often in real code.

In this lesson you will learn

  • The lambda arguments: expression syntax
  • How a lambda compares with a def function
  • map, filter and functools.reduce
  • Sorting with sorted(..., key=...) and reverse=True
  • Using key with max and min

You should already know how to write Python functions.

Lambda Syntax, map, filter and reduce

square = lambda x: x * x
add = lambda a, b: a + b
print(square(7), add(3, 4))

# The same function written with def
def square_def(x):
    return x * x
print(square_def(7) == square(7))

nums = [4, 11, 8, 3, 15, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))

from functools import reduce
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))

# A comprehension is often clearer than map/filter
print([n * 10 for n in nums if n % 2 == 0])

Output

49 7
True
[40, 110, 80, 30, 150, 60]
[4, 8, 6]
120
[40, 80, 60]
  • lambda x: x * x takes one argument and returns x * x. The body must be a single expression, and its value is returned automatically; there is no return keyword.
  • A lambda is exactly equivalent to a small def function. Assigning a lambda to a name, as with square here, works but is discouraged by the PEP 8 style guide; use def when a function needs a name.
  • map(fn, items) applies a function to every item. filter(fn, items) keeps items for which the function returns true. Both return lazy iterators, so list() is used to see the results.
  • reduce, from functools, combines the items pairwise into one value: ((((1×2)×3)×4)×5) = 120.
  • A list comprehension often does the same job as map and filter and is usually easier to read.

Sorting With key

students = [
    ("Nusrat", "CSE", 3.82),
    ("Arif", "EEE", 3.41),
    ("Tania", "CSE", 3.95),
    ("Rafi", "EEE", 2.98),
]

by_cgpa = sorted(students, key=lambda s: s[2], reverse=True)
for name, dept, cgpa in by_cgpa:
    print(f"{name:7} {cgpa}")

# Sort by department, then by CGPA (highest first) inside each department
by_dept = sorted(students, key=lambda s: (s[1], -s[2]))
print([s[0] for s in by_dept])

words = ["banana", "Cherry", "apple", "Date"]
print(sorted(words))                       # capital letters sort first
print(sorted(words, key=str.lower))        # case-insensitive
print(max(words, key=len), min(words, key=len))

prices = {"pen": 20, "bag": 950, "book": 300}
print(sorted(prices.items(), key=lambda kv: kv[1]))

Output

Tania   3.95
Nusrat  3.82
Arif    3.41
Rafi    2.98
['Tania', 'Nusrat', 'Arif', 'Rafi']
['Cherry', 'Date', 'apple', 'banana']
['apple', 'banana', 'Cherry', 'Date']
banana Date
[('pen', 20), ('book', 300), ('bag', 950)]
  • sorted(items, key=fn) calls fn on each item and sorts by the results. key=lambda s: s[2] sorts students by their CGPA, the third field.
  • reverse=True sorts from largest to smallest.
  • A key can return a tuple to sort by several fields: (s[1], -s[2]) sorts by department, then by CGPA descending (the minus sign reverses the numeric order).
  • Plain sorted(words) puts capital letters before lowercase ones because it compares character codes. key=str.lower gives a case-insensitive order; an existing function can be passed directly without a lambda.
  • max and min accept key too. When two items tie, as “banana” and “Cherry” do on length, the first one wins.
  • dict.items() gives (key, value) pairs, so key=lambda kv: kv[1] sorts a dictionary by its values.
  • list.sort() sorts a list in place; sorted() returns a new list and works on any iterable. Python’s sort is stable: items with equal keys keep their original order.

lambda vs def

lambdadef
NameAnonymousNamed
BodyOne expressionAny number of statements
ReturnAutomaticUses return
Docstring and type hintsNoYes
Best forShort throw-away logic passed to another functionEverything else

Common Mistakes

  1. Writing statements in a lambda, such as an assignment or if block; only expressions are allowed. A conditional expression works: lambda n: "even" if n % 2 == 0 else "odd".
  2. Forgetting list() around map or filter and printing a map object.
  3. Lambdas in a loop that all use the loop variable’s final value: [lambda: i for i in range(3)] all return 2. Bind it with a default: lambda i=i: i.
  4. Squeezing complex logic into one lambda; a named function is clearer and easier to test.

Practice Exercises

Exercise 1. Sort the list ["kiwi", "fig", "banana", "apple"] by word length, shortest first.

Show answer
print(sorted(["kiwi", "fig", "banana", "apple"], key=len))
# ['fig', 'kiwi', 'apple', 'banana']

Exercise 2. Use filter and a lambda to keep only the names that start with a vowel.

Show answer
names = ["Arif", "Nadia", "Imran", "Rafi", "Omar"]
print(list(filter(lambda n: n[0].lower() in "aeiou", names)))
# ['Arif', 'Imran', 'Omar']

Frequently Asked Questions

Why is it called lambda?

The name comes from lambda calculus, a mathematical system for describing functions created by Alonzo Church in the 1930s. Many languages use the word for anonymous functions.

Can a lambda take no arguments or several?

Yes. lambda: 42 takes none, and lambda a, b, c=0: a + b + c takes several, including defaults.

Summary

  • lambda args: expression creates a small anonymous function.
  • Pass lambdas to sorted, max, min, map and filter.
  • Sort by several fields with a tuple key; use reverse=True for descending.
  • Prefer def for anything longer than one simple expression.

Next: Python *args and **kwargs.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *