๐ Day 13 : Lambda Functions
๐ฏ Enterprise Objective
Functional programming treats computation as the evaluation of mathematical functions. Today we master lambda, map, filter, and reduce. These patterns are essential for writing clean data transformation pipelines, especially in Pandas.
๐ Strategic Overview
| # | Topic | Concept |
|---|---|---|
| 1 | Lambdas | Anonymous inline functions |
| 2 | Functional | Map, Filter, Reduce |
1. Lambda Functions : Anonymous Inline Functions
A lambda is a small, anonymous, single-line function. Defined using lambda arguments: expression. It implicitly returns the result of the expression.
# Standard
def add(x, y): return x + y
# Lambda
add_lambda = lambda x, y: x + y
๐ผ Why Data Analysts Care
โข Pandas Apply: df['col'].apply(lambda x: x * 2) โ inline data transformations
โข Sorting: sorted(data, key=lambda d: d['age']) โ custom sort keys on the fly
โ ๏ธ Overusing Lambdas
If a lambda gets complex or requires multiple lines, write a standard def function instead. Code readability is more important than brevity.
๐งช Concept Checks: Lambdas
Q1. Write a lambda that multiplies a number by 10. Assign it to times10. Call it with 5.
Q2. Use a lambda with sorted() to sort words = ["apple", "banana", "cherry", "date"] by length.
Q3. Given a list of dicts [{"id": 2}, {"id": 1}], sort them by "id" using a lambda key.
Q4. Create a lambda that takes x, y and returns True if x > y. Call it with 10, 5.
Q5. Extract the domain from an email: lambda email: email.split("@")[1]. Test it on "user@gmail.com".
2. Map, Filter, Reduce : Functional Paradigms
Python supports functional programming concepts. map() applies a function to all items. filter() keeps items where a function returns True. reduce() (from functools) repeatedly applies a function to pairs of items to reduce a list to a single value.
| Function | Purpose | Equivalent Comprehension |
|---|---|---|
map(f, data) | Transform | [f(x) for x in data] |
filter(f, data) | Extract | [x for x in data if f(x)] |
reduce(f, data) | Aggregate | (No direct equivalent) |
๐ผ Why Data Analysts Care
โข Data Pipelines: Chaining operations: reduce(add, map(square, filter(is_even, data)))
โข Legacy Code: You will see map/filter frequently in codebases written by Java/JS developers
๐ง Pro Tip
In modern Python, list comprehensions are generally preferred over map() and filter() because they are more readable and slightly faster.
๐งช Concept Checks: Functional
Q1. Use map() and a lambda to convert names = ["alice", "bob"] to uppercase. Print as list.
Q2. Use filter() and a lambda to extract numbers > 5 from [3, 8, 2, 9, 4]. Print as list.
Q3. Import reduce. Use it to find the maximum value in [1, 5, 2, 8, 3] using a lambda.
Q4. Write a list comprehension that does the exact same thing as list(map(lambda x: x**2, [1, 2, 3])).
Q5. Why does map() return a instead of a list? (Hint: Lazy evaluation).
๐ ๏ธ Professional Practice Tasks
Theory is useless without muscle memory. Complete these tasks to solidify your understanding.
Task 1 (Sort by Length): Given sentences = ['I am Python', 'Hi', 'This is a long sentence'], sort them by word count using sorted() and a lambda. Print the result.
Task 2 (Data Pipeline): Given nums = [1, -5, 10, -2, 8]. Use filter() to remove negatives, then map() to square them, then reduce() to sum them up. Print the final sum.
Task 3 (Dictionary Filter): Given a dictionary data = {'a': 10, 'b': 5, 'c': 20}, use filter() and a lambda on data.items() to keep pairs where value > 5. Convert back to dict.
Task 4 (Multi-Map): Given A = [1, 2, 3] and B = [10, 20, 30]. Use map() with a lambda lambda x, y: x + y to add them element-wise. Print the resulting list.
Task 5 (Custom Reduce): Write your own my_reduce(func, seq) function using a for loop that mimics the behavior of functools.reduce.
๐ป Pure Coding Interview Questions
Q1.
Write a lambda that takes a string and returns the number of vowels in it. Test with 'hello world'.
Q2.
Write the same transformation using list(map(lambda x: x2, data)) and [x2 for x in data]. Time both on a list of 100,000 numbers and print which is faster.
Q3.
Write a lambda to extract the domain from an email address (e.g., 'user@gmail.com' โ 'gmail.com'). Test with 3 emails.
Q4.
Use functools.reduce to concatenate ['Hello', ' ', 'World'] into a single string 'Hello World'.
Q5.
Write a reduce() call that computes the product of [1, 2, 3, 4, 5]. Then write the same logic using a for loop. Print both results.
Q6.
Write a filter() expression that removes all None values from [1, None, 2, None, 3]. Print the result as a list.
Q7.
Write code to sort a dictionary {'b': 3, 'a': 1, 'c': 2} by its values in descending order using sorted() with a lambda key.
Q8.
Write a custom my_map(func, iterable) generator function using yield. Test it with my_map(str.upper, ['a', 'b']).
Q9.
Import functools.partial. Create add_ten = partial(add, 10) from def add(a, b): return a + b. Call add_ten(5) and print.
Q10.
Write a function make_counter() that returns an inner function. Each call to the inner function increments and returns a counter. Demonstrate the closure.
Q11.
Write a pipeline: use filter to get even numbers from range(20), then map to square them. Print the result as a list.
Q12.
Write two versions of uppercasing a word list: list(map(str.upper, words)) and list(map(lambda x: x.upper(), words)). Print both results.
Q13.
Given [(1, 'a'), (3, 'c'), (2, 'b')], sort by the second element using a lambda key. Print the sorted list.
Q14.
Write a lambda that checks if a string reads the same forwards and backwards (palindrome). Test with 'racecar' and 'hello'.
Q15.
Write a lambda that classifies a number as 'positive', 'negative', or 'zero' using nested ternary. Test with -5, 0, 7.
Q16.
Use reduce to find the intersection of [{1,2,3}, {2,3,4}, {3,4,5}]. Print the result.
Q17.
Write your own my_any(iterable) function using functools.reduce. It should return True if any element is truthy.
Q18.
Write code that creates a map object of 1 million squares. Print its size using sys.getsizeof() vs the equivalent list's size.
Q19.
Write a lambda that takes another function as an argument and calls it twice: twice = lambda f, x: f(f(x)). Test with lambda x: x + 3.
Q20.
Write code using map with lambda over a list of tuples [(1,2), (3,4)] to compute each tuple's sum. Print the result.
Q21.
Write code demonstrating the late-binding closure bug: funcs = [lambda: i for i in range(3)]. Call each and print the (unexpected) results.
Q22.
Fix the late-binding bug from the previous question using lambda i=i: i. Call each and verify they return 0, 1, 2.
Q23.
Use filter and a lambda to keep only words containing the letter 'e' from ['hello', 'world', 'test', 'fun'].
Q24.
Write a lambda that parses '2023-12-25' and returns a tuple (2023, 12, 25) using split and map(int, ...).
Q25.
Write a lambda that has a side effect (appends to a list). Call it 3 times and print the list to show the mutation.
๐ Day 13 Executive Summary
| # | Topic | Key Takeaway |
|---|---|---|
| 1 | Lambda | lambda x: x*2 is great for apply() |
| 2 | Map/Filter | Lazy evaluation saves memory |
โ Instructor's End-of-Day Checklist
โข [ ] I can write a lambda function.
โข [ ] I can use map() and filter().
โข [ ] I understand reduce().