Small tools for sorting, transforming, filtering, and grouping data
Functional tools help you express data flow directly: sort this, transform that, keep matching values, group related rows. They are useful when they make the operation clearer than a manual loop.
Use sorted when you want a new ordered list, key= when the sort depends on a derived value, and lazy tools like map, filter, and itertools when values can flow one at a time.
sort mutates the list in place; sorted returns a new sorted list leaving the original unchanged. The key= argument lets you sort by any derived value.
Sort is stable: equal items keep their original order. Use key= whenever you hear "sort by".
map transforms every element, filter keeps only matching elements, reduce folds a sequence into one value. All return lazy iterators — wrap in list() to materialise.
Use map with named functions, comprehensions for simple inline logic, and reduce rarely. Built-ins like sum, min, and max are usually clearer.
itertools provides composable building blocks for working with iterables — flattening, grouping, and chaining — all lazily without loading data into memory.
groupby only groups consecutive matching keys, so sort by the same key first. Reach for itertools when a loop is mostly glue code.