How to Use Lambda Functions in Python
Learn how to create and use anonymous lambda functions in Python for concise, inline operations.
Lambda functions are small, anonymous functions defined with a single expression. They’re useful for short operations, especially with higher-order functions.
Basic Syntax
# Regular function
def add(x, y):
return x + y
# Lambda equivalent
add = lambda x, y: x + y
print(add(3, 5)) # 8
Lambda vs Regular Functions
# Lambda: single expression, implicit return
square = lambda x: x ** 2
# Regular: multiple statements, explicit return
def square(x):
return x ** 2
# Both work the same
print(square(4)) # 16
Using with Built-in Functions
sorted() and sort()
# Sort by custom key
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78}
]
# Sort by grade
by_grade = sorted(students, key=lambda s: s["grade"])
print([s["name"] for s in by_grade]) # ['Charlie', 'Alice', 'Bob']
# Sort descending
by_grade_desc = sorted(students, key=lambda s: s["grade"], reverse=True)
# Sort strings by length
words = ["apple", "pie", "banana", "a"]
by_length = sorted(words, key=lambda w: len(w))
print(by_length) # ['a', 'pie', 'apple', 'banana']
map()
Transform each element:
numbers = [1, 2, 3, 4, 5]
# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Convert to strings
strings = list(map(lambda x: str(x), numbers))
# Or simply: list(map(str, numbers))
filter()
Keep elements matching condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# Keep non-empty strings
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(lambda w: w, words))
print(non_empty) # ['hello', 'world', 'python']
reduce()
Accumulate values:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Sum all numbers
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
# Find maximum
maximum = reduce(lambda a, b: a if a > b else b, numbers)
print(maximum) # 5
# Concatenate strings
words = ["Hello", " ", "World"]
sentence = reduce(lambda a, b: a + b, words)
print(sentence) # "Hello World"
Multiple Arguments
# Two arguments
add = lambda x, y: x + y
print(add(3, 5)) # 8
# Multiple arguments
concat = lambda *args: " ".join(args)
print(concat("Hello", "World")) # "Hello World"
# With default values
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Alice")) # "Hello, Alice!"
print(greet("Bob", "Hi")) # "Hi, Bob!"
Conditional Expressions
# Ternary in lambda
max_val = lambda a, b: a if a > b else b
print(max_val(5, 3)) # 5
# Classify numbers
classify = lambda x: "positive" if x > 0 else "negative" if x < 0 else "zero"
print(classify(5)) # "positive"
print(classify(-3)) # "negative"
print(classify(0)) # "zero"
Practical Examples
Sorting Complex Data
# Sort by multiple keys
data = [
("Alice", 30, 50000),
("Bob", 25, 60000),
("Charlie", 30, 55000)
]
# Sort by age, then by salary descending
sorted_data = sorted(data, key=lambda x: (x[1], -x[2]))
print(sorted_data)
# [('Bob', 25, 60000), ('Charlie', 30, 55000), ('Alice', 30, 50000)]
Dictionary Operations
# Find key with max value
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
top_scorer = max(scores, key=lambda k: scores[k])
print(top_scorer) # "Bob"
# Sort dictionary by value
sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
print(sorted_scores) # {'Bob': 92, 'Alice': 85, 'Charlie': 78}
Data Cleaning
# Clean and transform data
raw_data = [" Alice ", "BOB", " charlie"]
cleaned = list(map(lambda s: s.strip().title(), raw_data))
print(cleaned) # ['Alice', 'Bob', 'Charlie']
# Filter valid entries
data = [("Alice", 25), ("", 30), ("Bob", None), ("Charlie", 35)]
valid = list(filter(lambda x: x[0] and x[1], data))
print(valid) # [('Alice', 25), ('Charlie', 35)]
Event Handlers
# GUI callback example
# button.bind("<Click>", lambda event: print("Clicked!"))
# Creating function variants
def make_multiplier(n):
return lambda x: x * n
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
When NOT to Use Lambda
# Don't use for complex logic
# Bad
process = lambda x: x ** 2 if x > 0 else abs(x) if x < 0 else 0
# Better as regular function
def process(x):
if x > 0:
return x ** 2
elif x < 0:
return abs(x)
return 0
# Don't assign to variable if you're just going to call it once
# Bad
f = lambda x: x * 2
result = f(5)
# Better
result = 5 * 2
# Or if needed in a function context, just use a regular function
Summary
- Lambda syntax:
lambda arguments: expression - Single expression only, implicit return
- Great with
map(),filter(),sorted(),reduce() - Can have multiple arguments and default values
- Use for simple, one-off operations
- Use regular functions for complex logic or reusability