Lambda, map, filter & sorted
Python · Intermediate
Definition
A lambda is a small anonymous function; map transforms, filter selects and sorted orders using a key.
Makes data transformations short and readable.
Diagram
Flowchart
Example: Pipeline
nums = [1, 2, 3, 4]
print(list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums))))
print(sorted(['bb', 'a', 'ccc'], key=len))Output: [4, 16] ['a', 'bb', 'ccc']
Complexity
sorted is O(n log n)
Key points
- Comprehensions are often clearer
- key=lambda can sort by multiple fields with tuples
Interview questions
sort() vs sorted()?
list.sort() sorts in place; sorted() returns a new list.