Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Lambda Functions
Lambda functions are small, anonymous (unnamed) functions defined in one line. They're commonly used with map(), filter(), and sorted() for quick transformations.
Lambda Functions
# Regular function
def add(a, b):
return a + b
# Lambda equivalent
add_lambda = lambda a, b: a + b
print(add_lambda(5, 3)) # 8
# Lambda with sorted()
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
sorted_by_score = sorted(students, key=lambda s: s[1], reverse=True)
print(sorted_by_score)
# Lambda with map() - transform every element
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
# Lambda with filter() - keep matching elements
evens = list(filter(lambda x: x % 2 == 0, range(20)))
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# When to use lambda vs def:
# - Simple, one-expression functions: lambda
# - Complex logic, multiple lines, docstrings: defTip
Tip
Use lambda with sorted(key=lambda x: x[1]) and filter(lambda x: x > 0, list). For anything beyond one expression, use def.
One expression only. Shines in higher-order functions.
Common Mistake
Warning
Don't assign lambda to a variable as a substitute for def. Use def add(a,b): return a+b instead of add = lambda a,b: a+b. PEP 8 discourages this.
Practice Task
Note
(1) Sort a list of tuples by the second element using lambda. (2) Filter even numbers with filter+lambda. (3) Double all values with map+lambda.