Python Mastery – From Basics to Brilliance / Functions

First Class Functions

πŸ₯‡ First-Class Functions

In Python, functions are first-class objects. This means a function can be treated like any other value.

A function can be:

  • Stored in a variable

  • Passed as an argument

  • Returned from another function

  • Stored in a list, tuple, or dictionary


1️⃣ Store a Function in a Variable

def greet():
    print("Hello!")

message = greet

message() #Hello!

Here, message refers to the greet function.


2️⃣ Pass a Function as an Argument

A function can be passed to another function.

def greet():
    print("Hello!")

def execute(function):
    function()

execute(greet) #Hello!

Here, greet is passed as an argument to execute().


3️⃣ Return a Function

A function can also return another function.

def outer():
    def inner():
        print("Hello!")

    return inner

result = outer()
result() #Hello!

4️⃣ Store Functions in a List

Functions can even be stored inside a list.

def add():
    print("Adding")

def subtract():
    print("Subtracting")

operations = [add, subtract]

operations[0]() #Adding
operations[1]() #Subtracting

⭐ Why is this Important?

First-class functions are the foundation for concepts such as:

πŸ”Ή Higher-Order Functions
πŸ”Ή Lambda Functions
πŸ”Ή Decorators
πŸ”Ή Callbacks
πŸ”Ή Functional Programming

🧠 Remember

First-Class Function = A function can be treated like a normal values.