First Class Function: Python

Function are the code block which contain a logic to process on certain set of given input and return an output. Functions in Python are the First Class Object which basically means function as entity can be

Some functions are also called as Higher Order Function which means that a function which take other function as an argument or return a function as result. Example of higher order function in Python are Map, Filter, Sorted ...

Let see in Python function are classes or not and try to prove above all points to show in Python Function are First Class Object.

Creating function at run-time in console.

def add(x, y):
    return x+y

add(2, 4)
<class 'function'>

Assigned to the variable

sum = add
<function add at 0x7f2199555b70>
// notice above sum variable pointing to the add function.
sum(3, 4)

Passing function as argument.

list(map(add, range(5), range(5))) // here we pass *add* function as argument to the *map* function.
[0, 2, 4, 6, 8]

Returning function as result.

def factorial(x):
    if x < 1:
        return 1
        return x * factorial(x-1) // here we are returning a function

Above code snippets clearly show that function in Python are First Class Object.