Three operations, three different jobs.
map() transforms every item, filter() keeps only items that pass a condition, and sorted() creates an ordered list. In Python 3, map and filter return iterators, so list() often makes their results visible.
prices = [100, 200, 300]
discounted = list(map(lambda price: price * 0.9, prices))
print(discounted)map() calls the lambda for every price. list() collects its iterator into [90.0, 180.0, 270.0]; prices stays unchanged.
[90.0, 180.0, 270.0]filter() keeps original items whose condition is true. sorted() returns a new list, while list.sort() changes a list in place and returns None.
Choose the clearest form: A comprehension is often easier to read for a small transformation or filter. map() and filter() are useful when you already have a function to pass.
scores = [45, 82, 67, 91, 38]
passed = list(filter(lambda score: score >= 60, scores))
products = [{"name": "Mouse", "price": 20}, {"name": "Keyboard", "price": 45}, {"name": "Monitor", "price": 180}]
ordered = sorted(products, key=lambda product: product["price"], reverse=True)
numbers = [1, 2, 3, 4, 5]
with_map = list(map(lambda n: n * 2, numbers))
with_comprehension = [n * 2 for n in numbers]filter() returns the passing scores without changing them. sorted() can use reverse=True for descending order and is stable: equal keys keep their original order.
available = filter(lambda product: product["price"] >= 50, products)
discounted = map(lambda product: product["price"] * 0.9, available)The filter decides which products continue. map() then changes only their prices.
ordered = sorted(products, key=lambda product: product["price"])sorted() leaves products unchanged. Use .sort() only when changing that same list is intended.
Follow the data pipeline
- 1. Start with original dataBegin with a small collection of values or dictionaries.
- 2. filter() selectsIts function returns True for elements that stay.
- 3. map() transformsIts function returns the new value for every remaining element.
- 4. sorted() ordersIt returns a new list in ascending order unless reverse=True is used.
Common mistakes
- Expecting map() to be a listWrap map() or filter() in list() when you need a list to print or reuse.
- Mixing selection and transformationfilter() keeps original elements; map() creates transformed values.
- Expecting sorted() to mutatesorted() returns a new list. list.sort() mutates the list and returns None.
- Making one long chainName intermediate results when nesting map(), filter(), and lambda makes code hard to read.
