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

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

  • Object: Methods and properties

    🚗 Car Properties ⚙️ Car Methods 🚗 Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: ⚙️ Car Methods Methods are the verbs that describe what a car can do….

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

Leave a Reply

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