Python functions are a fundamental building block of any program. Advanced functions in Python take this concept further, offering more sophisticated and powerful capabilities. Here's an overview of some advanced Python functions and their uses.

Recursion

Recursion is a method where the solution to a problem depends on solutions to smaller instances of the same problem. A classic example is calculating the factorial of a number.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # Output: 120

Higher-Order Functions

Higher-order functions are functions that operate on or return other functions. They are widely used in Python for various purposes, such as sorting, filtering, and mapping.

def square(x):
    return x * x

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Lambda Functions

Lambda functions are anonymous functions defined with the lambda keyword. They are useful for creating small, throwaway functions that can be used as arguments to higher-order functions.

numbers = [1, 2, 3, 4, 5]
sorted_numbers = sorted(numbers, key=lambda x: x**2)
print(sorted_numbers)  # Output: [1, 4, 9, 16, 25]

Decorators

Decorators are a powerful feature in Python that allow you to modify the behavior of functions or methods. They are often used for logging, access control, and more.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Generator Functions

Generator functions are a powerful way to create iterators in Python. They allow you to generate a sequence of values without storing them all in memory at once.

def my_generator():
    for i in range(5):
        yield i

for value in my_generator():
    print(value)

For more information on advanced Python functions, check out our Python Functions Guide.


Advanced Python Functions