?? Functional Programming in Python: Beyond the Basics
Varun Pandey
Strategic Principal Engineer | Program Management Expert | Innovator in Advanced Technologies (Python, Computer Vision) | DevOps and Automation Specialist | Proven Track Record in Lean Practices | Python Coach
Python, known for its versatility, also embraces functional programming paradigms. ???? Let's take a deeper dive beyond the basics and explore how functional programming concepts can enhance your Pythonic code.
1. First-Class Functions:
def square(x):
return x ** 2
# Function assigned to a variable
my_func = square
# Function passed as an argument
def apply(func, value):
return func(value)
result = apply(square, 5)
2. Lambda Functions:
# Traditional function
def add(x, y):
return x + y
# Equivalent lambda function
add_lambda = lambda x, y: x + y
3. Map, Filter, and Reduce:
numbers = [1, 2, 3, 4, 5]
# Map: Apply a function to each element
squared_numbers = list(map(lambda x: x ** 2, numbers))
# Filter: Filter elements based on a condition
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# Reduce: Aggregate elements to a single value
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
领英推荐
4. Immutability and Side Effects:
# Immutability
original_list = [1, 2, 3]
new_list = original_list + [4] # Create a new list
# Pure function
def multiply_by_two(x):
return x * 2
# Side effect: Modifying external state
global_variable = 0
def increment_global():
global global_variable
global_variable += 1
In the example above, calling increment_global() has a side effect on the global_variable outside the function.
5. Recursion:
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
Elevate Your Code: