←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Functions in Python, Lambda, map(), filter() & reduce()

Study material and explanations for Unit 2

Functions in Python: Types, Lambda, map(), filter() & reduce()

For marks 40, 55 and 70, map can add five to each mark, filter can keep only marks above 50, and reduce can combine them into one total. A lambda is a short function expression that any of these operations can receive.

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:

  1. Code Reusability: Write once, call multiple times.
  2. Modularity: Breaks a large complex program into smaller, manageable parts.
  3. 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

A built-in function is supplied by Python and a user-defined function is written with def. A lambda expression creates a function whose body is a single expression.

Types of Function Arguments in Python:

  1. Positional Arguments: Passed in the exact order of parameters (add(10, 20)).
  2. Keyword Arguments: Passed using parameter names (student(name="Riya", roll=101)), so order doesn’t matter.
  3. Default Arguments: Parameters given a default value (def greet(name="Guest"):).
  4. 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

View diagram · Types of Functions in Python


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 return keyword 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.

Map transforms each input and filter keeps inputs that pass a test. Reduce combines the sequence into one accumulated result.

A. 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 functools module (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

View diagram · How map(), filter(), and reduce() Work on [1, 2, 3, 4]