Home »
Python
Python First-Class Functions with Examples
Last Updated : April 24, 2025
In Python, a function is a type. That's why Python function is known as "First class". So,
- We can pass function as parameter to another function
- We can return function as return value
- We can define a new function inside another function (this feature is known as "Closure")
1. Pass function as parameter to another function
Python allows passing a function as a parameter to another function.
Example
# defining a function
def foo():
print("I am foo()")
# defining another function which is receiving
# function as parameter
def koo(x):
x()
# calling second function and passing first function
# as parameter
koo(foo)
Output
I am foo()
2. Return function as return value
Python allows returning a function as its return value.
Example
# defining first function
def foo():
print("I am foo()")
# defining second function which is returning
# first function as return value
def koo():
return foo
# calling second function and recieving
# reference of first function
x = koo()
x()
Output
I am foo()
3. Define a new function inside another function
Python allows defining a new function inside a function.
Example
# Function inside function
# definition of parent function
def foo():
# definition of child function
def koo():
print("I am koo()")
print("I am foo()")
koo()
foo()
# koo() cannot be called here, because
# it's scope is limited to foo() only
# koo() # it will not work
Output
I am foo()
I am koo()
Python First-Class Functions Exercise
Select the correct option to complete each statement about first-class functions in Python.
- In Python, functions are treated as ___, which means they can be assigned to variables, passed as arguments, and returned from other functions.
- A function that takes another function as an argument is known as a ___.
- Returning a function from another function is an example of using functions as ___.
Advertisement
Advertisement