Skip to main content
Python for Beginners
CHAPTER 14 Beginner

Lambda Functions and Higher-Order Functions

Updated: May 17, 2026
20 min read

# Lambda Functions and Higher-Order Functions

Welcome to Chapter 14! Lambda functions are small, anonymous functions defined in a single line. Combined with map(), filter(), and reduce(), they enable powerful functional programming patterns.

---

1. Learning Objectives

  • Write lambda (anonymous) functions.
  • Use map(), filter(), and reduce().
  • Understand higher-order functions.
  • Know when to use lambdas vs regular functions.

---

2. Lambda Functions

```python id="py14_ex1" # Regular function def square(x): return x 2

# Lambda equivalent square = lambda x: x 2

print(square(5)) # 25

# Lambda with multiple parameters add = lambda a, b: a + b print(add(3, 7)) # 10

# Lambda with conditional check = lambda x: "even" if x % 2 == 0 else "odd" print(check(4)) # even print(check(7)) # odd

123456
---

## 3. map() Function

Applies a function to every item in an iterable:

python id="py14ex2" numbers = [1, 2, 3, 4, 5]

# Square each number squares = list(map(lambda x: x**2, numbers)) print(squares) # [1, 4, 9, 16, 25]

# Convert strings to uppercase names = ["alice", "bob", "charlie"] uppernames = list(map(str.upper, names)) print(uppernames) # ['ALICE', 'BOB', 'CHARLIE']

# Multiple iterables a = [1, 2, 3] b = [10, 20, 30] sums = list(map(lambda x, y: x + y, a, b)) print(sums) # [11, 22, 33]

# Convert list of strings to integers strnums = ["1", "2", "3", "4"] intnums = list(map(int, strnums)) print(int_nums) # [1, 2, 3, 4]

123456
---

## 4. filter() Function

Filters elements based on a condition:

python id="py14ex3" numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get even numbers evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4, 6, 8, 10]

# Filter non-empty strings words = ["hello", "", "world", "", "python"] nonempty = list(filter(None, words)) # None removes falsy values print(non_empty) # ['hello', 'world', 'python']

# Filter students who passed students = [("Alice", 85), ("Bob", 42), ("Charlie", 91), ("Diana", 38)] passed = list(filter(lambda s: s[1] >= 50, students)) print(passed) # [('Alice', 85), ('Charlie', 91)]

123456
---

## 5. reduce() Function

Reduces an iterable to a single value by accumulating:

python id="py14_ex4" from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Sum all numbers total = reduce(lambda a, b: a + b, numbers) print(f"Sum: {total}") # 15

# Product of all numbers product = reduce(lambda a, b: a * b, numbers) print(f"Product: {product}") # 120

# Find maximum maximum = reduce(lambda a, b: a if a > b else b, numbers) print(f"Max: {maximum}") # 5

1

reduce() step by step: [1, 2, 3, 4, 5] Step 1: 1 + 2 = 3 Step 2: 3 + 3 = 6 Step 3: 6 + 4 = 10 Step 4: 10 + 5 = 15 ← Final result

123456
---

## 6. Higher-Order Functions

Functions that accept or return other functions:

python id="py14ex5" # Function that returns a function def multiplier(factor): return lambda x: x * factor

double = multiplier(2) triple = multiplier(3)

print(double(5)) # 10 print(triple(5)) # 15

# Sorting with key function students = [("Alice", 85), ("Charlie", 91), ("Bob", 72)] byscore = sorted(students, key=lambda s: s[1], reverse=True) print(byscore) # [('Charlie', 91), ('Alice', 85), ('Bob', 72)]

# Dictionary sorting by value scores = {"Alice": 85, "Bob": 72, "Charlie": 91} sortedscores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True)) print(sorted_scores)

1234
---

## 7. Combining map, filter, reduce

python id="py14_ex6" numbers = range(1, 11)

# Get sum of squares of even numbers result = reduce( lambda a, b: a + b, map(lambda x: x2, filter(lambda x: x % 2 == 0, numbers)) ) print(f"Sum of squares of evens: {result}") # 220

# List comprehension alternative (more Pythonic) result2 = sum(x2 for x in range(1, 11) if x % 2 == 0) print(f"Same result: {result2}") # 220 ``

---

8. Lambda vs Regular Functions

FeatureLambdaRegular Function
SyntaxSingle expressionMultiple statements
NameAnonymousNamed
ReadabilityShort operationsComplex logic
DebuggingHarderEasier
DocstringsNoYes

Rule of thumb: Use lambdas for simple, one-time operations. Use regular functions for anything else.

---

9. Common Mistakes

  1. 1. Multi-line lambdas: Lambda only supports single expressions.
  1. 2. Overusing lambdas: When logic is complex, use a named function.
  1. 3. Forgetting list() with map/filter: They return iterators, not lists.
  1. 4. Not importing reduce: from functools import reduce.

---

10. MCQs with Answers

Q1: Lambda functions are also called: A) Named functions B) Anonymous functions C) Class methods D) Generators Answer: B

Q2: map() returns: A) List B) Tuple C) Iterator D) Set Answer: C — Wrap with list() to get a list.

Q3: filter(None, [0, 1, "", "hi"]) returns: A) [0, 1, "", "hi"] B) [1, "hi"] C) [0, ""] D) Error Answer: B — Removes falsy values.

Q4: reduce is in which module? A) os B) sys C) functools D) itertools Answer: C

Q5: Lambda can have: A) Multiple expressions B) Single expression only C) No parameters D) No return Answer: B

Q6: sorted(lst, key=lambda x: -x) sorts: A) Ascending B) Descending C) Randomly D) Error Answer: B

Q7: list(map(str, [1,2,3])) returns: A) [1,2,3] B) ["1","2","3"] C) "123" D) Error Answer: B

Q8: Higher-order function: A) Uses recursion B) Takes/returns functions C) Has many params D) Uses classes Answer: B

Q9: Can lambda have default parameters? A) Yes B) No Answer: A — lambda x, y=10: x + y

Q10: Which is more Pythonic for simple filtering? A) filter() B) List comprehension C) for loop D) while loop Answer: B — List comprehensions are generally preferred.

---

11. Interview Questions

  1. 1. What is a lambda function? An anonymous, single-expression function defined with lambda.
  1. 2. map vs list comprehension? Both transform data; comprehensions are more Pythonic and readable.
  1. 3. What is a higher-order function? A function that takes functions as arguments or returns functions.
  1. 4. When to use reduce? For accumulating a sequence into a single value (sum, product, max).
  1. 5. Are lambdas faster than regular functions? No measurable difference; choose based on readability.

---

12. Summary

  • Lambda: lambda params: expression — anonymous, single-expression functions.
  • map(func, iterable) — applies function to each element.
  • filter(func, iterable) — keeps elements where function returns True.
  • reduce(func, iterable)` — accumulates elements into a single value.
  • Higher-order functions take or return functions.
  • Prefer list comprehensions over map/filter for readability.

---

13. Next Chapter Recommendation

In Chapter 15: Python Modules and Packages, you'll learn to organize code with modules, packages, pip, and virtual environments! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·