Lambda Functions

15 min In Progress

Learning Objectives

  • Write small anonymous functions with lambda
  • Use lambda with map, filter, and sorted

Lambda Syntax

A lambda is a small, unnamed function defined in a single line.

square = lambda x: x ** 2
print(square(5))

Course Example: Power Lambda

A lambda that calculates a number raised to a given power.

answer = lambda number, power : number ** power

print(answer(2, 3))
print(answer(5, 2))

Using Lambda with Built-ins

Lambdas shine when used as short callbacks.

names = ["Alice", "bob", "Charlie", "diana"]
names.sort(key=lambda n: n.lower())
print(names)

📝 Exercise: Lambda Filter

Use filter() with a lambda to get only the even numbers from the list.

code.py
Output

            
← Back to Chapter