First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be passed as arguments to other functions, returned as values from other functions, assigned to variables and stored in data structures.
Characteristics of First-Class Functions
- Assigned to Variables: We can assign functions to variables.
- Passed as Arguments: We can pass functions as arguments to other functions.
- Returned from Functions: Functions can return other functions.
- Stored in Data Structures: Functions can be stored in data structures such as lists, dictionaries, etc.
Assigning Functions to Variables
We can assign a function to a variable and use the variable to call the function.
Example:
def msg(name):
return f"Hello, {name}!"
# Assigning the function to a variable
f = msg
# Calling the function using the variable
print(f("Anurag"))
Output
Hello, Anurag!
Explanation:
- function greet is assigned to the variable f.
- f is then used to call the function, demonstrating that functions can be treated like any other variable.
Passing Functions as Arguments
Functions can be passed as arguments to other functions, enabling higher-order functions.
Example:
def msg(name):
return f"Hello, {name}!"
def fun1(fun2, name):
return fun2(name)
# Passing the greet function as an argument
print(fun1(msg, "Bob"))
Output
Hello, Bob!
Explanation:
- The fun1 function takes another function fun2 and a name as arguments.
- The msg function is passed to fun1, which then calls greet with the given name.
Returning Functions from Other Functions
A function can return another function, allowing for the creation of function factories.
Example:
def fun1(msg):
def fun2():
return f"Message: {msg}"
return fun2
# Getting the inner function
func = fun1("Hello, World!")
print(func())
Output
Message: Hello, World!
Explanation:
- The fun1 defines an fun2 and returns it.
- func stores the returned fun2, which can then be called later.
Storing Functions in Data Structures
Functions can be stored in data structures like lists or dictionaries.
Example:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
# Storing functions in a dictionary
d = {
"add": add,
"subtract": subtract
}
# Calling functions from the dictionary
print(d["add"](5, 3))
print(d["subtract"](5, 3))
Output
8 2
Explanation:
- Functions add and subtract are stored in a dictionary operations.
- Functions are accessed and called from the dictionary using their respective keys.