Skip to content

Instantly share code, notes, and snippets.

@theSamyak
Last active June 14, 2024 20:53
Show Gist options
  • Save theSamyak/e48ba06b8a65d53cbb857a3f323a8b98 to your computer and use it in GitHub Desktop.
Save theSamyak/e48ba06b8a65d53cbb857a3f323a8b98 to your computer and use it in GitHub Desktop.
Understanding First-Class Functions, High-Order Functions and Closures in Python: A Detailed Guide

First-Class Functions

Assigning Functions to Variables

Using Closures with Parameters

def outer_scope(name, city):
def inner_scope():
print(f"Hello {name}, Greetings from {city}")
return inner_scope
# Creating closures with different names and locations
greet_priyanshu = outer_scope('Dr Priyanshu', 'Jaipur')
greet_sam = outer_scope('Sam', 'New York')
# Executing the closures
greet_priyanshu() # Output: Hello Dr Priyanshu, Greetings from Jaipur
greet_sam() # Output: Hello Sam, Greetings from New York
def add(a, b):
return a + b
result = add(3, 4)
print(add) # Prints the function object
print(result) # Prints 7

Passing Functions as Arguments

def double(n):
return n * 2
def map_function(func, values):
result = []
for value in values:
result.append(func(value))
return result
# Use the custom map function
doubled_values = map_function(double, [3, 6, 9, 12, 15])
print(doubled_values) # Output: [6, 12, 18, 24, 30]

Returning Functions from Other Functions

def create_multiplier(factor):
"""Returns a function that multiplies its input by the given factor."""
def multiplier(x):
return x * factor
return multiplier
# Create specific multiplier functions
double = create_multiplier(2)
triple = create_multiplier(3)
# Use the created functions
print(double(5)) # Output: 10
print(triple(5)) # Output: 15

Higher Order Function

A higher-order function that takes a function as an argument

def apply_operation(operation, x, y):
return operation(x, y)
# Functions to pass as arguments
def add(x, y):
return x + y
def multiply(x, y):
return x * y
# Using the higher-order function
result_add = apply_operation(add, 3, 4)
result_multiply = apply_operation(multiply, 3, 4)
print(result_add) # Output: 7
print(result_multiply) # Output: 12

A higher-order function that returns another function

def discount_applier(discount_rate):
def apply_discount(price):
return price - (price * discount_rate / 100)
return apply_discount
# Creating closures with different discount rates
holiday_discount = discount_applier(20)
member_discount = discount_applier(15)
# Applying the discounts
print(holiday_discount(100)) # Output: 80.0
print(member_discount(100)) # Output: 85.0

Lambda Functions

Using Lambda Functions in a Custom Map Function

def map_function(func, values):
return [func(value) for value in values]
# Using a lambda function as the argument
doubled_values = map_function(lambda n: n * 2, [3, 6, 9, 12, 15])
print(doubled_values) # Output: [6, 12, 18, 24, 30]

Creating Multiplier Functions with Lambdas

def create_multiplier(factor):
return lambda x: x * factor
# Create specific multiplier functions
double = create_multiplier(2)
triple = create_multiplier(3)
# Use the created functions
print(double(5)) # Output: 10
print(triple(5)) # Output: 15

Closure

Basic Nested Function with Immediate Execution

def outer_scope():
name = 'Sam'
city = 'New York'
def inner_scope():
print(f"Hello {name}, Greetings from {city}")
return inner_scope()
outer_scope()

Returning the Inner Function

def outer_scope():
name = 'Sam'
city = 'New York'
def inner_scope():
print(f"Hello {name}, Greetings from {city}")
return inner_scope
# Assigning the inner function to a variable
greeting_func = outer_scope()
# Calling the inner function
greeting_func()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment