- Built-in functions ā Python's ready-to-use functions
- User-defined functions ā creating your own functions
- Lambda functions ā anonymous one-liner functions
- Recursive functions ā functions that call themselves
- Higher-order functions ā functions that operate on other functions
- When to use each type ā choosing the right function type
Introduction to Function Types
Python provides several types of functions, each serving different purposes. Understanding the different types helps you choose the right tool for the job and write more efficient, readable code.
š” Key concept: Python functions can be classified into multiple categories based on how they are defined, where they come from, and how they behave. The main types are built-in, user-defined, lambda, recursive, and higher-order functions.
Built-in Functions
Python's Ready-to-Use Functions
# Python comes with many built-in functions ready to use
# No need to import them ā they're always available
# 1. Type Conversion Functions
print(int("123")) # 123 ā convert string to integer
print(float("45.67")) # 45.67 ā convert to float
print(str(100)) # "100" ā convert to string
print(list("abc")) # ['a', 'b', 'c'] ā convert to list
print(tuple([1, 2, 3])) # (1, 2, 3) ā convert to tuple
print(dict([("a", 1), ("b", 2)])) # {'a': 1, 'b': 2}
# 2. Math Functions
print(abs(-10)) # 10 ā absolute value
print(max(5, 10, 3)) # 10 ā maximum value
print(min(5, 10, 3)) # 3 ā minimum value
print(sum([1, 2, 3, 4])) # 10 ā sum of elements
print(pow(2, 3)) # 8 ā 2 raised to power 3
print(round(3.14159, 2)) # 3.14 ā round to 2 decimal places
# 3. Sequence Functions
numbers = [3, 1, 4, 1, 5]
print(len(numbers)) # 5 ā length of sequence
print(sorted(numbers)) # [1, 1, 3, 4, 5] ā sorted list
print(sum(numbers)) # 14 ā sum of elements
print(min(numbers)) # 1 ā minimum value
print(max(numbers)) # 5 ā maximum value
# 4. Input/Output Functions
# print() ā display output
# input() ā get user input
# 5. Type Checking Functions
print(type(10)) #
print(isinstance(10, int)) # True
print(isinstance("hello", str)) # True
# 6. Other Useful Built-ins
print(all([True, True, False])) # False ā all elements True?
print(any([True, False, False])) # True ā any element True?
print(enumerate(["a", "b", "c"])) # enumerate object
print(zip([1, 2], ["a", "b"])) # zip object
Categories of built-in functions:
- Type Conversion ā int(), str(), list(), tuple()
- Mathematical ā abs(), max(), min(), sum(), round()
- Sequence Operations ā len(), sorted(), reversed()
- Type Checking ā type(), isinstance()
- Input/Output ā print(), input()
- Iteration Helpers ā enumerate(), zip(), map()
Quick Check: What is a built-in function? (Answer: A function that comes with Python and is always available without importing)
User-Defined Functions
Creating Your Own Functions
# User-defined functions are created using the 'def' keyword
# 1. Simple function ā no parameters, no return
def greet():
"""Print a greeting"""
print("Hello, World!")
greet() # Hello, World!
# 2. Function with parameters
def greet_person(name):
"""Greet a specific person"""
print(f"Hello, {name}!")
greet_person("Alice") # Hello, Alice!
# 3. Function with return value
def add(a, b):
"""Add two numbers and return the result"""
return a + b
result = add(5, 3)
print(result) # 8
# 4. Function with default parameters
def greet_user(name="Guest"):
"""Greet a user with a default name"""
return f"Welcome, {name}!"
print(greet_user()) # Welcome, Guest!
print(greet_user("Bob")) # Welcome, Bob!
# 5. Function with multiple return values
def get_user_info():
"""Return multiple values as a tuple"""
return "Alice", 25, "Engineer"
name, age, job = get_user_info()
print(f"{name} is {age} and works as {job}")
# 6. Function with variable arguments (*args)
def sum_all(*args):
"""Sum any number of arguments"""
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
# 7. Function with keyword arguments (**kwargs)
def print_info(**kwargs):
"""Print key-value pairs"""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="NYC")
User-defined function features:
- Created with def keyword
- Can have parameters (inputs)
- Can have return values (outputs)
- Can have default parameters
- Can accept variable arguments (*args, **kwargs)
- Can have docstrings for documentation
Quick Check: What keyword is used to create a user-defined function? (Answer: def)
Lambda Functions (Anonymous Functions)
One-Liner Anonymous Functions
# Lambda functions are small, anonymous functions
# Syntax: lambda arguments: expression
# 1. Simple lambda function
square = lambda x: x ** 2
print(square(5)) # 25
# 2. Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 4)) # 7
# 3. Lambda with conditional expression
is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(4)) # Even
print(is_even(7)) # Odd
# 4. Lambda with map() ā apply to all elements
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 5. Lambda with filter() ā filter elements
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# 6. Lambda with sorted() ā custom sorting
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
sorted_by_age = sorted(people, key=lambda x: x["age"])
print(sorted_by_age) # Sorted by age
# 7. Lambda with reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product) # 24
Lambda function characteristics:
- Anonymous ā no function name
- Single expression ā can only have one line
- Returns automatically ā the expression is returned
- Best for simple operations ā not for complex logic
- Common with map(), filter(), sorted() ā functional programming
Quick Check: What is a lambda function? (Answer: An anonymous, single-expression function defined with the lambda keyword)
Recursive Functions
Functions That Call Themselves
# A recursive function calls itself to solve a problem
# Must have a base case to stop recursion
# 1. Factorial using recursion
def factorial(n):
"""Calculate n! using recursion"""
# Base case
if n <= 1:
return 1
# Recursive case
return n * factorial(n - 1)
print(factorial(5)) # 120 (5*4*3*2*1)
# 2. Fibonacci sequence
def fibonacci(n):
"""Calculate the nth Fibonacci number"""
# Base cases
if n <= 0:
return 0
if n == 1:
return 1
# Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(7)) # 13
print(fibonacci(10)) # 55
# 3. Sum of numbers from 1 to n
def sum_to_n(n):
"""Sum numbers from 1 to n"""
if n <= 0:
return 0
return n + sum_to_n(n - 1)
print(sum_to_n(10)) # 55
# 4. Power calculation
def power(base, exponent):
"""Calculate base^exponent recursively"""
if exponent == 0:
return 1
if exponent == 1:
return base
return base * power(base, exponent - 1)
print(power(2, 5)) # 32
print(power(3, 4)) # 81
# 5. List sum recursively
def recursive_sum(numbers):
"""Sum elements of a list recursively"""
if not numbers:
return 0
return numbers[0] + recursive_sum(numbers[1:])
print(recursive_sum([1, 2, 3, 4, 5])) # 15
# Important: Recursion has a depth limit
import sys
print(sys.getrecursionlimit()) # Default is 1000
Recursive function components:
- Base case ā condition to stop recursion
- Recursive case ā function calls itself
- Progress toward base case ā each call gets closer
- Depth limit ā Python limits recursion depth to 1000
- Best for tree-like structures ā directories, file systems
Quick Check: What is a recursive function? (Answer: A function that calls itself with a base case to stop)
Higher-Order Functions
Functions That Work With Other Functions
# Higher-order functions either:
# 1. Take other functions as arguments
# 2. Return functions as results
# 1. Function as argument
def apply_operation(operation, a, b):
"""Apply any operation to two numbers"""
return operation(a, b)
def add(x, y):
return x + y
def multiply(x, y):
return x * y
print(apply_operation(add, 5, 3)) # 8
print(apply_operation(multiply, 5, 3)) # 15
# 2. Using lambda with higher-order functions
print(apply_operation(lambda x, y: x - y, 10, 3)) # 7
# 3. Function returning a function
def create_multiplier(factor):
"""Create a function that multiplies by a factor"""
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
# 4. Decorators ā a common higher-order function pattern
def timer(func):
"""Decorator to measure execution time"""
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.6f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(0.1)
return "Done"
slow_function() # slow_function took 0.100001 seconds
# 5. Built-in higher-order functions
# map(), filter(), reduce(), sorted() with key
# map() ā apply function to all elements
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# filter() ā filter elements
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
Higher-order function concepts:
- Functions as arguments ā pass functions to other functions
- Functions as return values ā return functions from functions
- Decorators ā modify behavior of functions
- Functional programming tools ā map(), filter(), reduce()
- Closures ā functions that remember their environment
Quick Check: What is a higher-order function? (Answer: A function that takes other functions as arguments or returns functions)
Comparison of Function Types
When to Use Each Type
# Summary of function types
print("=" * 60)
print("FUNCTION TYPES COMPARISON")
print("=" * 60)
# 1. Built-in Functions
print("\nš BUILT-IN FUNCTIONS")
print(" - Examples: print(), len(), type(), sum(), max()")
print(" - When to use: Common operations that Python provides")
print(" - Advantages: Fast, optimized, always available")
print(" - Limitations: Limited to what Python provides")
# 2. User-Defined Functions
print("\nš USER-DEFINED FUNCTIONS")
print(" - Examples: def calculate_area(), def greet_user()")
print(" - When to use: Custom logic, reusable code")
print(" - Advantages: Flexible, readable, reusable")
print(" - Limitations: Need to write and maintain them")
# 3. Lambda Functions
print("\nš LAMBDA FUNCTIONS")
print(" - Examples: lambda x: x*2, lambda a,b: a+b")
print(" - When to use: Simple one-time operations")
print(" - Advantages: Concise, no function definition needed")
print(" - Limitations: Single expression only, less readable")
# 4. Recursive Functions
print("\nš RECURSIVE FUNCTIONS")
print(" - Examples: factorial(), fibonacci(), tree traversal")
print(" - When to use: Problems that have recursive structure")
print(" - Advantages: Elegant for certain problems")
print(" - Limitations: Depth limit, memory intensive")
# 5. Higher-Order Functions
print("\nš HIGHER-ORDER FUNCTIONS")
print(" - Examples: map(), filter(), decorators")
print(" - When to use: Functional programming, decorators")
print(" - Advantages: Powerful abstraction, reusable patterns")
print(" - Limitations: Can be complex, harder to debug")
Choosing the right function type:
- Built-in ā use when Python already provides it
- User-defined ā use for custom, reusable logic
- Lambda ā use for simple, one-time operations
- Recursive ā use for problems with recursive structure
- Higher-order ā use for functional programming patterns
Quick Check: When should you use a lambda function? (Answer: For simple, one-line operations where a full function definition isn't needed)
Try It Yourself
Experiment with different types of functions in the editor below.
TYPES OF FUNCTIONS PRACTICE
========================================
1. BUILT-IN FUNCTIONS
Numbers: [3, 1, 4, 1, 5, 9, 2, 6]
Length: 8
Sum: 31
Max: 9
Min: 1
Sorted: [1, 1, 2, 3, 4, 5, 6, 9]
2. USER-DEFINED FUNCTION
Hello, Alice!
5 + 3 = 8
3. LAMBDA FUNCTION
Square of 7: 49
Squared: [1, 4, 9, 16, 25]
4. RECURSIVE FUNCTION
Factorial of 5: 120
Factorial of 7: 5040
5. HIGHER-ORDER FUNCTION
5 * 4 = 20
10 + 5 = 15
Types of functions practice complete!
You've Got It!
You now understand the different types of functions in Python ā built-in, user-defined, lambda, recursive, and higher-order functions. You know when and how to use each type.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between built-in and user-defined functions?
When should I use a lambda function instead of a regular function?
What is the recursion limit in Python?
sys.getrecursionlimit() and modify it with sys.setrecursionlimit(), but be careful as deep recursion can cause stack overflow.
What is a decorator in Python?
What's a common interview question about function types?
Can a function be both recursive and anonymous?
Where to Go From Here
Now that you understand the different types of functions, check out these related topics:
Inbuilt Functions
Explore Python's most useful built-in functions in detail.
Learn More āUser-Defined Functions
Learn why and how to create your own functions.
Learn More āFunction Arguments
Master different types of function arguments.
Learn More ā