Python Lambda & Functions

Lambda functions, map, filter, and functional programming in Python.

Lambda Functions

# Basic lambda
add = lambda x, y: x + y
add(3, 5)  # 8

square = lambda x: x ** 2
square(5)  # 25

# Lambda with condition
is_even = lambda x: x % 2 == 0
is_even(4)  # True

# Lambda with multiple conditions
grade = lambda x: 'A' if x >= 90 else 'B' if x >= 80 else 'C'
grade(85)  # 'B'

Map Function

# Map with lambda
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]

# Map with function
def double(x):
    return x * 2

doubled = list(map(double, numbers))
# [2, 4, 6, 8, 10]

# Map with multiple iterables
a = [1, 2, 3]
b = [4, 5, 6]
sums = list(map(lambda x, y: x + y, a, b))
# [5, 7, 9]

Filter Function

# Filter with lambda
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6, 8, 10]

# Filter strings
words = ['apple', 'banana', 'cherry', 'date']
long_words = list(filter(lambda w: len(w) > 5, words))
# ['banana', 'cherry']

# Remove None/empty values
data = [0, 1, '', 'hello', None, 42]
filtered = list(filter(None, data))
# [1, 'hello', 42]

Reduce & Sorted

# Reduce (sum all)
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
# 15

# Reduce (multiply all)
product = reduce(lambda x, y: x * y, numbers)
# 120

# Sorted with key
words = ['apple', 'pie', 'banana']
sorted(words, key=lambda w: len(w))
# ['pie', 'apple', 'banana']

# Sort by second element
pairs = [(1, 3), (2, 1), (3, 2)]
sorted(pairs, key=lambda x: x[1])
# [(2, 1), (3, 2), (1, 3)]