Assign a Function to a Variable in Python

By James L.

In Python, functions are first-class objects. This means you can treat functions like any other object, such as integers, strings, or lists. 

You can assign functions to variables, pass them as arguments to other functions, store them in data structures like lists or dictionaries, and even have them returned from other functions.

# Assigning a function to a variable in Python

In Python, you can assign a function to a variable just like you would assign any other value to a variable. Just use the function’s name without parentheses. Parentheses execute the function, while a bare name assigns it.

Here’s an example:

# Define a function
def say_hello():
    print("Hello")


# Assign the function to a variable
greeting_function = say_hello

# Call the function through the variable
greeting_function()

In this example, the say_hello() function is assigned to the variable greeting_function.

To call the say_hello() function, you can simply use the variable greeting_function followed by parentheses.

# Assigning a function with arguments to a variable

Assigning a function with arguments to a variable is also pretty straightforward.

Here’s an example:

# Define a function with arguments
def say_hello(name):
    print(f"Hello, {name}!")


# Assign the function to a variable
greeting_function = say_hello

# Call the function through the variable with an argument
greeting_function("James Bond")  # Output: 'Hello, James Bond!'

In this example, the say_hello() function takes an argument name. The function is then assigned to the variable greeting_function.

Now you can call the say_hello() function with arguments using the greeting_function variable by simply placing parentheses directly after the variable name. You can pass arguments within the parentheses.

Conclusion

In conclusion, leveraging the first-class object nature of functions in Python gives us the ability to assign functions to variables, pass them as arguments, store them in data structures, and return them from other functions. This versatility opens up a world of possibilities for flexible and expressive coding.

Happy coding → 3000