Python Lambda, Map & Filter
PythonLambda functions are small anonymous functions. Combined with map() and filter(), they make data processing elegant.
Key Points
lambda— one-line anonymous functionmap(func, iterable)— apply function to every itemfilter(func, iterable)— keep items that return Truereduce()— combine all items into one value- These are common in interviews and real-world data processing
Example — PYTHON
# Lambda basics
square = lambda x: x ** 2
print(square(5))
add = lambda a, b: a + b
print(add(10, 20))
# Map — apply to all items
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(f"Squared: {squared}")
# Convert temperatures
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(f"Fahrenheit: {fahrenheit}")
# Filter — keep matching items
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")
# Filter students who passed
marks = [45, 78, 32, 91, 55, 28, 67]
passed = list(filter(lambda m: m >= 40, marks))
print(f"Passed: {passed}")
# Sorting with lambda
students = [
{"name": "Rahul", "marks": 85},
{"name": "Priya", "marks": 92},
{"name": "Amit", "marks": 78},
]
students.sort(key=lambda s: s["marks"], reverse=True)
for s in students:
print(f"{s[\"name\"]}: {s[\"marks\"]}")
# Reduce
from functools import reduce
nums = [1, 2, 3, 4, 5]
total = reduce(lambda a, b: a + b, nums)
print(f"Sum using reduce: {total}") Result
25
30
Squared: [1, 4, 9, 16, 25]
Fahrenheit: [32.0, 68.0, 98.6, 212.0]
Evens: [2, 4, 6, 8, 10]
Passed: [45, 78, 91, 55, 67]
Priya: 92
Rahul: 85
Amit: 78
Sum using reduce: 15
30
Squared: [1, 4, 9, 16, 25]
Fahrenheit: [32.0, 68.0, 98.6, 212.0]
Evens: [2, 4, 6, 8, 10]
Passed: [45, 78, 91, 55, 67]
Priya: 92
Rahul: 85
Amit: 78
Sum using reduce: 15