techmore.in

Python - Functional Programming

What is Functional Programming?

Functional programming is a programming paradigm where functions are treated as first-class citizens, allowing functions to be passed as arguments, returned from other functions, and assigned to variables.

Why Use It?

  • Improves readability and testability
  • Reduces side effects by avoiding shared state
  • Useful in data transformation pipelines

map()

map() applies a function to all items in an iterable and returns a new iterable.

python
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16]

filter()

filter() filters elements from an iterable based on a function that returns True or False.

python
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

reduce()

reduce() from the functools module applies a function cumulatively to the items in a sequence.

python
from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 24

Lambda Functions

Lambda functions are small anonymous functions defined with the lambda keyword. Often used with map, filter, and reduce.

python
add = lambda a, b: a + b
print(add(5, 3))  # 8

Higher-Order Functions

Functions that take other functions as arguments or return functions.

python
def shout(text):
    return text.upper()

def whisper(text):
    return text.lower()

def speak(style, message):
    return style(message)

print(speak(shout, "Hello"))  # HELLO
print(speak(whisper, "Hello"))  # hello

List Comprehensions

A concise way to create lists using loops and conditions.

python
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)  # [1, 4, 9, 16, 25]

Set and Dictionary Comprehensions

Similar to list comprehensions, but for sets and dictionaries.

python
numbers = [1, 2, 3, 4, 5]

# Set comprehension
evens = {x for x in numbers if x % 2 == 0}
print(evens)  # {2, 4}

# Dict comprehension
squares = {x: x ** 2 for x in numbers}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

When to Use Functional Programming?

  • When working with transformations or pipelines
  • For short, expressive logic
  • In scenarios where mutability should be avoided

Pros and Cons

  • Pros: Concise code, less side-effects, testable, composable functions
  • Cons: Can be harder to read for beginners, overuse of lambda may reduce readability