Functions in Python: Types, Lambda, map(), filter() & reduce()
A Function is a named, reusable block of code that performs a specific task. Instead of writing the same logic multiple times, we define a function once and call it whenever needed.
Advantages of Using Functions:
- Code Reusability: Write once, call multiple times.
- Modularity: Breaks a large complex program into smaller, manageable parts.
- Easier Debugging: Bugs can be isolated to a specific function.
1. Defining and Calling a Function
In Python, a function is defined using the def keyword followed by the function name, parentheses ( ), and a colon (:).
# Function Definition
def calculate_area(length, width):
"""Returns the area of a rectangle."""
area = length * width
return area
# Function Call
result = calculate_area(10, 5)
print("Area of Rectangle =", result) # Output: 50
2. Types of Functions in Python
print(), len(), type(), input(), max()def keywordlambdaTypes of Function Arguments in Python:
- Positional Arguments: Passed in the exact order of parameters (
add(10, 20)). - Keyword Arguments: Passed using parameter names (
student(name="Riya", roll=101)), so order doesn’t matter. - Default Arguments: Parameters given a default value (
def greet(name="Guest"):). - Variable-Length Arguments:
*args: Accepts any number of positional arguments as a Tuple.**kwargs: Accepts any number of keyword arguments as a Dictionary.
def total_marks(*marks):
return sum(marks)
print(total_marks(80, 85, 90)) # Output: 255
print(total_marks(70, 75, 80, 95)) # Output: 320
3. Lambda Function (Anonymous Function)
A Lambda Function is a small, anonymous (nameless) function defined using the lambda keyword instead of def.
- It can take any number of arguments, but can have only one expression.
- The result of the expression is automatically returned (no
returnkeyword needed).
Syntax:
lambda arguments : expression
Examples:
# 1. Lambda function to find square of a number
square = lambda x: x * x
print(square(6)) # Output: 36
# 2. Lambda function to add two numbers
add = lambda a, b: a + b
print(add(15, 25)) # Output: 40
# 3. Lambda function with if-else to find maximum of two numbers
maximum = lambda a, b: a if a > b else b
print(maximum(12, 9)) # Output: 12
| Feature | Normal Function (def) |
Lambda Function (lambda) |
|---|---|---|
| Keyword | Defined using def |
Defined using lambda |
| Function Name | Must have a name | Anonymous (nameless) |
| Number of Lines | Can have multiple lines & statements | Single-line expression only |
| Return Statement | Requires explicit return |
Implicitly returns expression result |
4. Functional Programming Tools: map(), filter(), and reduce()
Python provides three classic higher-order functions that take a function (often a lambda) and a sequence as arguments.
[1, 2, 3, 4] → square → [1, 4, 9, 16]True.[1, 2, 3, 4] → even → [2, 4][1, 2, 3, 4] → sum → 10A. The map() Function
Applies a given function to every item of an iterable (like a list) and returns a new mapped collection.
Syntax: map(function, iterable)
nums = [1, 2, 3, 4, 5]
# Double every number in the list using map() and lambda
doubled = list(map(lambda x: x * 2, nums))
print(doubled) # Output: [2, 4, 6, 8, 10]
B. The filter() Function
Filters elements from a sequence by testing each item with a function that returns True or False. Only items returning True are kept.
Syntax: filter(function, iterable)
nums = [10, 15, 22, 33, 40, 55]
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [10, 22, 40]
C. The reduce() Function
Applies a rolling computation to sequential pairs of values in a list and reduces the entire list down to a single cumulative value.
- Available in the built-in
functoolsmodule (from functools import reduce).
Syntax: reduce(function, iterable)
from functools import reduce
nums = [1, 2, 3, 4, 5]
# Multiply all elements together: (((1 * 2) * 3) * 4) * 5
product = reduce(lambda a, b: a * b, nums)
print("Product =", product) # Output: 120