Functions as Parameters in Python

Functions as Parameters in Python

In Python, functions are first-class objects, which means they can be:

  • Assigned to variables
  • Passed as arguments to other functions
  • Returned from other functions

Basic Concept

When we pass a function as a parameter, we’re essentially allowing one function to use another function’s behavior.

Simple Examples

Example 1: Basic Function as Parameter

python

def greet(name):
    return f"Hello, {name}!"

def farewell(name):
    return f"Goodbye, {name}!"

def message_handler(func, name):
    """Takes a function and applies it to a name"""
    return func(name)

# Using different functions as parameters
print(message_handler(greet, "Alice"))      # Output: Hello, Alice!
print(message_handler(farewell, "Bob"))     # Output: Goodbye, Bob!

Example 2: Math Operations

python

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

def calculate(operation, x, y):
    """Performs the given operation on x and y"""
    return operation(x, y)

# Using the calculator
result1 = calculate(add, 5, 3)          # Output: 8
result2 = calculate(multiply, 5, 3)     # Output: 15

print(f"Addition: {result1}")
print(f"Multiplication: {result2}")

Example 3: Filtering with Custom Criteria

python

def is_even(n):
    return n % 2 == 0

def is_positive(n):
    return n > 0

def filter_numbers(numbers, criteria):
    """Filters numbers based on the given criteria function"""
    return [n for n in numbers if criteria(n)]

numbers = [-3, -2, -1, 0, 1, 2, 3, 4, 5]

even_numbers = filter_numbers(numbers, is_even)
positive_numbers = filter_numbers(numbers, is_positive)

print(f"Even numbers: {even_numbers}")        # Output: [-2, 0, 2, 4]
print(f"Positive numbers: {positive_numbers}") # Output: [1, 2, 3, 4, 5]

Example 4: Sorting with Custom Key

python

def by_length(word):
    return len(word)

def by_last_letter(word):
    return word[-1]

def custom_sort(words, key_func):
    """Sorts words using the provided key function"""
    return sorted(words, key=key_func)

words = ["apple", "banana", "cherry", "date", "elderberry"]

# Sort by word length
sorted_by_length = custom_sort(words, by_length)
print(f"Sorted by length: {sorted_by_length}")

# Sort by last letter
sorted_by_last_letter = custom_sort(words, by_last_letter)
print(f"Sorted by last letter: {sorted_by_last_letter}")

Example 5: Using Lambda Functions (Anonymous Functions)

python

def apply_operation(numbers, operation):
    """Applies operation to each number"""
    return [operation(n) for n in numbers]

numbers = [1, 2, 3, 4, 5]

# Using lambda functions as parameters
squared = apply_operation(numbers, lambda x: x ** 2)
doubled = apply_operation(numbers, lambda x: x * 2)
incremented = apply_operation(numbers, lambda x: x + 1)

print(f"Squared: {squared}")        # Output: [1, 4, 9, 16, 25]
print(f"Doubled: {doubled}")        # Output: [2, 4, 6, 8, 10]
print(f"Incremented: {incremented}") # Output: [2, 3, 4, 5, 6]

Key Benefits

  1. Flexibility: You can change behavior without modifying the main function
  2. Reusability: The same function can work with different operations
  3. Abstraction: Hide implementation details while exposing functionality
  4. Callback Pattern: Essential for event-driven programming and asynchronous operations

Common Use Cases

  • Custom sorting and filtering
  • Mathematical operations and transformations
  • Event handlers and callbacks
  • Strategy pattern implementation
  • Higher-order functions like map()filter(), and reduce()

This concept is fundamental to functional programming and is widely used in Python for creating flexible and reusable code.

Similar Posts

  • What is list

    In Python, a list is a built-in data structure that represents an ordered, mutable (changeable), and heterogeneous (can contain different data types) collection of elements. Lists are one of the most commonly used data structures in Python due to their flexibility and dynamic nature. Definition of a List in Python: Example: python my_list = [1, “hello”, 3.14,…

  • For loop 13 and 14th class

    The range() Function in Python The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times. Basic Syntax There are three ways to use range(): 1. range(stop) – One Parameter Form Generates numbers from 0 up to (but not including) the stop value. python for i in range(5):…

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

Leave a Reply

Your email address will not be published. Required fields are marked *