Lesson 28/48 Β· βš™οΈ Functions
βš™οΈ FunctionsLesson 28/48
Phase 4 Β· Functions15 min

Lambda Functions

One-line anonymous functions, perfect for sort keys and quick transforms

A lambda is a tiny, anonymous function you write in a single line. It's not a replacement for regular functions, it's a shortcut for simple operations passed as arguments.
Lambda syntaxpython
# Regular function
def double(x):
    return x * 2

# Same thing as a lambda
double = lambda x: x * 2

print(double(5))   # 10
Syntax: lambda parameters: expression
A lambda can have multiple parameters but only one expression (no statements, no loops, no if/else blocks, though you can use ternary).
Where lambdas shine, sorting
The most common use: passing a sort key to sorted() or list.sort():
Lambda as sort keypython
people = [
    {"name": "Charlie", "age": 30},
    {"name": "Alice",   "age": 25},
    {"name": "Bob",     "age": 35},
]

# Sort by age
by_age = sorted(people, key=lambda p: p["age"])
for p in by_age:
    print(p["name"], p["age"])
# Alice 25, Charlie 30, Bob 35

# Sort strings by length
words = ["banana", "fig", "apple", "kiwi"]
print(sorted(words, key=lambda w: len(w)))
# ['fig', 'kiwi', 'apple', 'banana']
map() and filter() with lambda
  • map(fn, iterable), apply fn to every element, return transformed sequence
  • filter(fn, iterable), keep only elements where fn returns True
  • map and filterpython
    numbers = [1, 2, 3, 4, 5, 6]
    
    # Double every number
    doubled = list(map(lambda x: x * 2, numbers))
    print(doubled)   # [2, 4, 6, 8, 10, 12]
    
    # Keep only evens
    evens = list(filter(lambda x: x % 2 == 0, numbers))
    print(evens)     # [2, 4, 6]
    In modern Python, list comprehensions are usually preferred over map/filter for readability. But you'll see map/filter often in existing code, and they're handy to know.
    πŸ€”Quick Check

    What does sorted(["cat","elephant","ox"], key=lambda w: len(w)) return?

    🎯

    Phase Complete!

    Functions

    Why do we write functions? Describe the DRY principle in your own words. Write a mini function definition (in your head or here) that you could use in a real DevOps script.

    0/500

    Practice Exercises

    0/3 solved
    Exercise 1 of 3easy
    ⏱ 00:00

    Sort by Last Name

    Sort the list of full names by last name (the word after the space).
    Given: names = ["Alice Smith", "Charlie Brown", "Bob Adams"]Expected output: ['Bob Adams', 'Charlie Brown', 'Alice Smith']
    solution.py
    1 / 3
    Exercise 2 of 3easy
    ⏱ 00:00

    Filter Long Words

    Use filter() with a lambda to keep only words longer than 4 characters.
    Given: words = ["hi", "Python", "is", "great", "and", "fun"]Expected output: ['Python', 'great']
    solution.py
    2 / 3
    Exercise 3 of 3easy
    ⏱ 00:00

    Sort Products by Price

    Sort a list of (name, price) tuples from cheapest to most expensive.
    Given: products = [("Widget", 9.99), ("Gadget", 4.99), ("Doohickey", 14.99)]Expected output: [('Gadget', 4.99), ('Widget', 9.99), ('Doohickey', 14.99)]
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion