15.1 Introduction to Lambda Functions
A lambda function is a small anonymous function written in one line. It is useful when you need a short function for a simple task and do not want to create a full function with def. Lambda functions can accept arguments and return one expression result.
Example
double = lambda number: number * 2
print(double(5))
Output
10
Output Explanation: The lambda receives 5, multiplies it by 2, and returns 10. The print() function displays that returned value.
15.2 Lambda Syntax
The basic lambda syntax uses the keyword lambda, followed by one or more arguments, a colon, and one expression. Python automatically returns the result of the expression. A lambda cannot contain several normal statements, so it is best for short and clear operations.
Example
add = lambda a, b: a + b
print(add(4, 6))
Output
10
Output Explanation: The lambda accepts 4 and 6 as a and b. It adds them and automatically returns 10.
15.3 Lambda Arguments
Lambda functions can accept zero, one, or many arguments. The arguments work like parameters in regular functions. Their values are supplied when the lambda is called. This makes lambdas useful for quick calculations, sorting rules, and data transformations.
Example
greet = lambda name: "Hello " + name
print(greet("Sara"))
Output
Hello Sara
Output Explanation: The argument name receives Sara. The expression joins Hello with Sara and returns the completed greeting.
15.4 Lambda Expressions
A lambda expression contains one expression whose value becomes the function result. Expressions can perform arithmetic, comparisons, conditional choices, or call other functions. Because only one expression is allowed, complicated logic should usually be placed in a regular function.
Example
maximum = lambda a, b: a if a > b else b
print(maximum(8, 3))
Output
8
Output Explanation: Python checks whether 8 is greater than 3. The condition is true, so the lambda returns 8.
15.5 Lambda vs Regular Functions
Lambda functions are short and anonymous, while regular functions created with def can contain many statements, comments, loops, and documentation. Use lambda for a small temporary operation. Use def when the logic is longer, reused often, or needs a clear descriptive name.
Example
square_lambda = lambda x: x ** 2
def square_regular(x):
return x ** 2
print(square_lambda(4))
print(square_regular(4))
Output
16
16
Output Explanation: Both functions calculate 4 squared. They use different syntax but return the same result, so both output 16.
15.6 Using Lambda with `sorted()`
The sorted() function can use a lambda as its key argument. The lambda tells Python which part of each item should be used for sorting. This is especially helpful when sorting words by length, records by a field, or tuples by one position.
Example
words = ["banana", "fig", "apple"]
result = sorted(words, key=lambda word: len(word))
print(result)
Output
['fig', 'apple', 'banana']
Output Explanation: The lambda returns the length of each word. sorted() arranges the words from the shortest length to the longest.
15.7 Using Lambda with `map()`
The map() function applies a function to every item in an iterable. A lambda is often used when the transformation is simple. map() returns a map object, so beginners usually convert it to a list to display or use all results easily.
Example
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Output
[2, 4, 6, 8]
Output Explanation: The lambda multiplies every number by 2. map() processes all four items, and list() collects the results.
15.8 Using Lambda with `filter()`
The filter() function keeps only items for which a function returns True. A lambda can provide a short condition. This is useful for selecting even numbers, valid names, passing scores, or records that meet a rule.
Example
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output
[2, 4, 6]
Output Explanation: The lambda checks whether each number has a remainder of zero when divided by 2. Only the even numbers are kept.
15.9 The `reduce()` Function
reduce() combines all items in an iterable into one final value. It is found in the functools module. The function repeatedly combines the accumulated result with the next item. It is useful for totals, products, and other cumulative calculations.
Example
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, numbers)
print(total)
Output
10
Output Explanation: reduce() first adds 1 and 2, then adds 3, and finally adds 4. The final accumulated result is 10.
15.10 Higher-Order Functions
A higher-order function accepts another function as an argument, returns a function, or both. map(), filter(), and sorted() are examples because they can receive functions. This idea allows code to become flexible and reusable without repeating similar logic.
Example
def apply_operation(value, operation):
return operation(value)
result = apply_operation(5, lambda x: x * 3)
print(result)
Output
15
Output Explanation: apply_operation receives both the number 5 and a lambda. It calls the lambda with 5, producing 15.
15.11 First-Class Functions
Python treats functions as first-class objects. This means a function can be stored in a variable, passed to another function, or returned from a function. This ability is the foundation of callbacks, decorators, higher-order functions, and functional programming techniques.
Example
def greet(name):
return "Hello " + name
message_function = greet
print(message_function("Ali"))
Output
Hello Ali
Output Explanation: The variable message_function refers to the greet function. Calling it with Ali produces the same greeting as calling greet directly.
15.12 Closures
A closure is an inner function that remembers values from its enclosing function even after the outer function has finished. Closures are useful for creating customized functions that preserve settings or data without using global variables.
Example
def make_multiplier(factor):
return lambda number: number * factor
double = make_multiplier(2)
print(double(7))
Output
14
Output Explanation: make_multiplier creates a lambda that remembers factor as 2. Later, double multiplies 7 by the remembered value.
15.13 Function Composition
Function composition means combining functions so that the output of one becomes the input of another. It helps break a problem into small reusable steps. The functions can then be connected in different orders to create new behavior.
Example
double = lambda x: x * 2
add_one = lambda x: x + 1
result = add_one(double(5))
print(result)
Output
11
Output Explanation: double(5) returns 10. That result is passed to add_one(), which adds 1 and returns 11.
15.14 Partial Functions
A partial function creates a new function with some arguments already filled in. Python provides partial() in the functools module. This is useful when you repeatedly call a function with one or more arguments that usually stay the same.
Example
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5))
Output
25
Output Explanation: partial() creates square with exponent fixed at 2. Calling square(5) calculates 5 raised to the power of 2.
15.15 `operator` Module
The operator module provides function versions of common operators such as addition, multiplication, and item access. These functions can be passed directly to map(), reduce(), sorted(), and other higher-order functions, sometimes making code clearer than a lambda.
Example
from operator import add
print(add(7, 3))
Output
10
Output Explanation: operator.add performs the same operation as 7 + 3. It receives two values and returns their sum.
15.16 Functional Programming Concepts
Functional programming focuses on using functions, avoiding unnecessary changes to data, and combining small operations. Common ideas include pure functions, immutability, first-class functions, map, filter, reduce, and function composition. Python supports these ideas while also supporting other programming styles.
Example
numbers = [1, 2, 3]
result = list(map(lambda x: x + 10, numbers))
print(result)
Output
[11, 12, 13]
Output Explanation: The original list remains unchanged. map() creates transformed values by adding 10 to every item.
15.17 Pure Functions
A pure function always produces the same output for the same input and does not change data outside itself. Pure functions are easier to test, understand, and reuse because they do not depend on hidden state or unexpected side effects.
Example
def calculate_tax(price):
return price * 0.13
print(calculate_tax(100))
Output
13.0
Output Explanation: The function uses only the provided price. For an input of 100, it always returns 13.0 and changes nothing outside the function.
15.18 Immutability
Immutability means data is not changed after it is created. Instead of modifying an existing value, a program creates a new value. Strings and tuples are immutable in Python. Functional programming often prefers this approach because it reduces unexpected changes.
Example
original = (1, 2, 3)
updated = original + (4,)
print(original)
print(updated)
Output
(1, 2, 3)
(1, 2, 3, 4)
Output Explanation: The original tuple is not changed. A new tuple is created by joining the original tuple with another one-item tuple.
15.19 Practical Functional Programming
Functional techniques are useful for cleaning data, transforming collections, filtering records, sorting information, and building processing pipelines. They work best when each step has a clear purpose. For beginners, readable code is more important than forcing every solution into one complicated expression.
Example
prices = [10, 25, 40]
discounted = list(map(lambda price: price * 0.9, prices))
print(discounted)
Output
[9.0, 22.5, 36.0]
Output Explanation: The lambda multiplies every price by 0.9, which applies a ten percent discount. map() returns all discounted values.
15.20 Chapter Practice Exercises
Practice exercises help you strengthen lambda and functional programming skills. Try writing short lambdas, sorting records, transforming lists with map(), selecting values with filter(), combining numbers with reduce(), and comparing lambda solutions with regular functions. Always test each solution and study the output.
Example
numbers = [2, 4, 6]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
Output
[4, 16, 36]
Output Explanation: This practice example squares every number. The lambda calculates each square, and map() processes the complete list.
15.21 Chapter Mini Project
In this mini project, you will process a list of student records using functional programming tools. You will filter passing students, sort them by score, and create readable result messages. This combines lambdas, filter(), sorted(), map(), and list conversion in one practical beginner project.
Example
students = [("Ali", 72), ("Sara", 91), ("Mina", 58)]
passing = filter(lambda student: student[1] >= 60, students)
ordered = sorted(passing, key=lambda student: student[1], reverse=True)
messages = list(map(lambda student: f"{student[0]}: {student[1]}", ordered))
print(messages)
Output
['Sara: 91', 'Ali: 72']
Output Explanation: filter() removes Mina because 58 is below 60. sorted() orders the remaining students by score from highest to lowest. map() creates readable messages.