Storing Functions in Variables

Lesson Introduction

Hello and welcome! Today's lesson explores a powerful feature of Python: storing functions in variables. This is useful for scenarios like callbacks, event handlers, or flexible program design. Our goal is to understand how to do this in Python.

By the end of this lesson, you'll know how to store functions in variables and utilize them effectively in your code.

Most importantly, we will learn how to treat objects as functions using callable objects, which will be very useful in future lessons.

Using Functions as First-Class Objects

First, let's explore how Python treats functions as first-class objects. This means you can assign functions to variables, pass them as arguments to other functions, and return them from other functions.

Consider a function to add two integers:

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

if __name__ == "__main__":
    print(add(1, 3)) # Output: 4

To store this function in a variable:

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

if __name__ == "__main__":
    # Assign the function to a variable
    fp = add

    # Use the function stored in the variable
    print("Using function stored in variable:", fp(2, 3))  # Output: Using function stored in variable: 5

Here, fp = add assigns the function add to the variable fp. We then call fp(2, 3) to use the add function through the variable fp.

Functions in Python are first-class objects because they can be passed around as arguments, returned from other functions, and assigned to variables. This makes them very flexible and powerful for dynamic behavior in your programs. In this lesson, we will cover ways of assigning a function to a variable. In the subsequent lessons you will learn about designing the higher-order functions which work with other functions as inputs or return values.

Lambda Expressions

Next, let's recall lambda expressions, a compact way to create small anonymous functions at runtime. Lambdas are particularly useful when you need a simple function for a short period.

Here's a comparison using a lambda function for the same add operation:

# Using lambda expression
add_lambda = lambda a, b: a + b

if __name__ == "__main__":
    print("Using lambda expression:", add_lambda(2, 3))  # Output: Using lambda expression: 5

Here, add_lambda = lambda a, b: a + b creates an anonymous function that adds two numbers and assigns it to the variable add_lambda.

Lambda expressions offer a concise way to define simple functions but should be used when the function's logic is straightforward and doesn't require extensive statements or complexity.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal