logo
30

Higher-Order Functions

⏱️ 30 min

Higher-Order Functions: Pass Rules as Arguments

What You Might Be Wondering

"Functions as arguments? That sounds abstract."

Think of it as pluggable rules: the process stays the same, but you swap out the rule.

One-Line Definition

A higher-order function is a function that takes another function as input or returns one as output.

Real-Life Analogy

A bubble tea ordering flow is always the same, but the sweetness rule is swappable (30% sugar, no sugar, etc.). Fixed process, interchangeable rule.

Minimal Working Example

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)  # [1, 4, 9, 16]

map and filter

nums = [1, 2, 3, 4, 5, 6]

evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # [2, 4, 6]
  • map: transforms each element
  • filter: keeps elements that pass a test

Quick Quiz (5 min)

  1. Use map to square a list.
  2. Use filter to keep numbers greater than 10.
  3. Given a list of orders, extract amounts then filter for high-value ones.

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Rewrite a for-based data cleaning snippet using map + filter. Compare readability.

Acceptance Criteria

You can independently:

  • Tell map and filter apart
  • Use higher-order functions for simple data pipelines
  • Know when to fall back to a regular for loop

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: higher-order functions are always better.

  • Reality: readability and team understanding come first.

  • Misconception: passing a non-callable where a function is expected.

  • Reality: if you see not callable, check the argument's type — you probably passed a value instead of a function.