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

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

Leave a Reply

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