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

Leave a Reply

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