Previous | Tutorial index | Next

Tutorial 6: Anonymous Functions – Lambda Expressions

Learning Objectives

Overview

Lambda functions (also called anonymous functions) are small, single‑expression functions that are defined without a name using the lambda keyword. They are typically used for short, throwaway operations where a full function definition would be unnecessarily verbose. Lambdas are a functional programming feature that allows you to write concise code, especially when working with higher‑order functions like map, filter, and sorted. However, they are limited to a single expression and cannot contain statements or multiple lines. In this tutorial, you will learn the syntax, typical use cases, and when to avoid them, as well as best practices for writing readable lambda expressions.

1. What Are Lambda Functions?

A lambda function is a small, anonymous function that can have any number of arguments but only one expression. It is defined using the lambda keyword. The result of the expression is automatically returned.

1.1 Syntax

lambda arguments: expression

1.2 Basic Example

# A lambda that squares a number square = lambda x: x ** 2 print(square(5)) # 25

This is equivalent to:

def square(x): return x ** 2

2. Key Differences Between Lambda and Regular Functions

Feature Lambda Functions Regular Functions (def)
Name Anonymous (no identifier) Named
Body Single expression only Multiple statements allowed
Return Implicitly returns the expression result Must use return explicitly
Statements Cannot contain statements (e.g., if, for, while, print, raise) Can contain any statements
Type annotations Not supported (but can be added via lambda with typing? Usually not) Supported
Documentation No docstring Can have docstring
Use cases Short, inline, one‑off functions Complex, reusable, documented logic

Example of lambda with no statements:

# Valid add = lambda a, b: a + b # Invalid: lambda cannot contain if-else as a statement, but it can use conditional expression # lambda x: if x > 0: return x else: return -x # SyntaxError # But conditional expression works: abs_value = lambda x: x if x >= 0 else -x

3. How to Call a Lambda Function

There are three common ways to invoke a lambda:

3.1 Assign to a Variable and Call

add = lambda x, y: x + y result = add(3, 4) # 7

3.2 Direct Call (Inline)

Wrap the lambda definition in parentheses and immediately pass arguments.

result = (lambda x, y: x + y)(3, 4) # 7

This is useful when you need a quick, one‑time computation.

3.3 Pass as an Argument to Another Function

This is the most common use case – passing lambdas to higher‑order functions like sorted, map, filter, and reduce.

4. Common Use Cases for Lambdas

4.1 Sorting with a Custom Key

The sorted() function and list.sort() accept a key function. Using a lambda allows you to sort by a specific attribute without defining a separate function.

people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)] # Sort by age (second element) people_sorted = sorted(people, key=lambda person: person[1]) print(people_sorted) # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]

4.2 Using map() to Apply a Function to Each Element

map(function, iterable) applies the function to every element and returns an iterator.

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

4.3 Using filter() to Select Elements

filter(function, iterable) keeps only elements for which the function returns True.

numbers = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4, 6]

4.4 Using reduce() for Cumulative Operations (from functools)

from functools import reduce product = reduce(lambda a, b: a * b, [1, 2, 3, 4]) print(product) # 24

4.5 In GUI/Event Handlers (e.g., Tkinter)

You can use a lambda to create a simple callback that passes additional arguments:

button = tk.Button(text="Click", command=lambda: print("Button clicked"))

5. Lambda Expressions with Conditional Logic

Although lambdas cannot contain statements, they can use conditional expressions (ternary operator).

max_value = lambda a, b: a if a > b else b print(max_value(10, 20)) # 20

6. Limitations and When to Avoid Lambdas

Rule of thumb: Use a lambda if the logic fits in a single line and the operation is obvious. Otherwise, define a regular function.

7. Advanced: Lambdas as First‑Class Objects

Like regular functions, lambdas are objects. You can store them in data structures, return them from functions, or use them as closures.

def make_multiplier(n): return lambda x: x * n times_3 = make_multiplier(3) print(times_3(10)) # 30

8. Best Practices

📝 Quiz – Check Your Understanding

  1. What is the correct syntax for a lambda that adds two numbers?

    Answer(A) `lambda a, b: a + b`
  2. Can a lambda function contain multiple statements?

    Answer(B) No, only a single expression.
  3. What does the following code output?

    f = lambda x: x * 2 print(f(3))
    Answer(A) `6`
  4. How do you call a lambda immediately without assigning it to a variable?

    Answer(B) `(lambda x: x+1)(5)`
  5. True or False: Lambda functions can have a docstring.

    AnswerFalse
  6. Which of the following is a valid use of a lambda with map?

    Answer(A) `map(lambda x: x**2, [1,2,3])`
  7. Given numbers = [1, 2, 3, 4], which code filters out odd numbers?

    Answer(A) `filter(lambda x: x % 2 == 0, numbers)`
  8. What is the main advantage of using a lambda over a named function for simple operations?

    Answer(B) It is more concise and can be defined inline.
  9. Which of the following is NOT a valid lambda expression?

    Answer(C) – `for` is a statement, not an expression.
  10. What is the result of (lambda x, y: x if x > y else y)(5, 3)?

    Answer(A) `5`

💻 Exercises – Practice Makes Perfect

Exercise 1: Basic Lambda
Write a lambda that computes the cube of a number. Assign it to a variable cube and test with 5.

Sample Solution ```python cube = lambda x: x ** 3 print(cube(5)) # 125 ```

Exercise 2: Sort by Length
Given words = ["apple", "kiwi", "banana", "pear"], use sorted() with a lambda to sort the list by string length (shortest first).

Sample Solution ```python words = ["apple", "kiwi", "banana", "pear"] sorted_words = sorted(words, key=lambda w: len(w)) print(sorted_words) # ['kiwi', 'pear', 'apple', 'banana'] ```

Exercise 3: Filter Strings with 'e'
Given fruits = ["apple", "banana", "cherry", "date", "elderberry"], use filter() with a lambda to get only fruits that contain the letter 'e'.

Sample Solution ```python fruits = ["apple", "banana", "cherry", "date", "elderberry"] result = list(filter(lambda f: 'e' in f, fruits)) print(result) # ['apple', 'cherry', 'date', 'elderberry'] ```

Exercise 4: Map to Square
Using map and a lambda, produce a list of squares of numbers from 0 to 9.

Sample Solution ```python squares = list(map(lambda x: x**2, range(10))) print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ```

Exercise 5: Conditional Lambda
Write a lambda that takes two numbers and returns the larger one using a conditional expression. Assign it to max_of_two and test.

Sample Solution ```python max_of_two = lambda a, b: a if a > b else b print(max_of_two(10, 20)) # 20 print(max_of_two(5, 3)) # 5 ```

🏠 Homework – Deeper Thinking

Short Answer Questions

1. Sorting by Multiple Criteria
Given employees = [("Alice", "Engineering", 75000), ("Bob", "Sales", 60000), ("Charlie", "Engineering", 80000), ("Diana", "Sales", 65000)], sort by department (ascending) and then by salary (descending) within each department using a lambda key.

Sample Answer ```python sorted_employees = sorted(employees, key=lambda emp: (emp[1], -emp[2])) print(sorted_employees) ```

2. Custom Reduce
Write a function my_reduce(iterable, func) that mimics reduce() using a loop. Test it with a lambda that multiplies numbers.

Sample Answer ```python def my_reduce(iterable, func): it = iter(iterable) try: result = next(it) except StopIteration: raise TypeError("empty iterable") for item in it: result = func(result, item) return result

print(my_reduce([2,3,4], lambda x,y: x*y)) # 24

</details> **3. Data Transformation with Lambdas** Given `students = {"Alice": [85, 92, 78], "Bob": [70, 65, 80], "Charlie": [90, 88, 95]}`, produce a new dictionary with average scores using a lambda. <details><summary>Sample Answer</summary> ```python students = {"Alice": [85, 92, 78], "Bob": [70, 65, 80], "Charlie": [90, 88, 95]} averages = {name: sum(scores)/len(scores) for name, scores in students.items()} print(averages)

Essay Questions

4. Lambda as Default Argument
Write a function make_adder(n) that returns a lambda that adds n. Use it to create add5 and add10.

Sample Answer ```python def make_adder(n): return lambda x: x + n

add5 = make_adder(5) add10 = make_adder(10) print(add5(10)) # 15 print(add10(10)) # 20

</details> **5. Chaining Lambdas** Define a lambda that takes a number and returns a lambda that multiplies by that number. Create a pipeline that squares a number then doubles it. <details><summary>Sample Answer</summary> ```python multiply_by = lambda factor: lambda x: x * factor double = multiply_by(2) square = lambda x: x * x pipeline = lambda x: double(square(x)) print(pipeline(3)) # 18

Homework Hints

Summary

In this tutorial, you have learned:

Lambdas are a powerful tool for concise functional programming in Python. When used appropriately, they can make your code more expressive and compact. However, they are not a replacement for regular functions and should be used sparingly when clarity is paramount.

Next Steps: In Tutorial 7, we will explore Higher‑Order Functions in detail, including map, filter, reduce, and the functools and itertools modules.

Happy lambdas!

Previous | Tutorial index | Next