Menu
Coddy logo textTech

Functions as Arguments

Lesson 3 of 12 in Coddy's Python Decorators course.

In Python, we can pass a function as an argument to another function.

For example,

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

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

def calculate(func, a, b):
    return func(a, b)

result = calculate(add_numbers, 2, 3)
print(result) # Output: 5

result = calculate(multiply_numbers, 2, 3)
print(result) # Output: 6

In this example, we define two functions: add_numbers and multiply_numbers.

We then define a third function called calculate, which takes a function func as its first argument, along with two additional arguments a and b.

When we call calculate, we pass the name of the function we want to use (either add_numbers or multiply_numbers) as the func argument, along with the two numbers we want to operate on.

The calculate function then calls the function func with the two numbers and returns the result.

In the example above, we call calculate twice: once with add_numbers and once with multiply_numbers.

The first call returns the sum of 2 and 3 (which is 5), and the second call returns the product of 2 and 3 (which is 6).

challenge icon

Challenge

Easy

Write a function called list_operator that takes a list of integers and an operator function as arguments.

The operator function should take two integers as input and return a single integer as output.

The list_operator function should apply the operator function to all pairs of adjacent integers in the list and return a new list with the results.

Here's an example of how the function should work:

>>> numbers = [1, 2, 3, 4, 5]
>>> result = list_operator(numbers, operator.add)
>>> result
[3, 5, 7, 9]

>>> numbers = [10, 20, 30, 40]
>>> result = list_operator(numbers, operator.mul)
>>> result
[200, 600, 1200]

Constraints

  • The input list will always contain at least two integers.
  • The operator function will always take two integers as input and return a single integer as output.

Note! The operator function is given by us, you don't need to create it, just use it.

Try it yourself

All lessons in Python Decorators