Lazy transformation
Convert or normalize each value without constructing an intermediate list immediately.
Python · Function
map() returns an iterator that applies a function to items from one or more iterables. With multiple inputs, it processes corresponding items in parallel and can require equal lengths with strict=True.
map() creates a lazy iterator that calls a function for each item in one iterable, or for corresponding items across several iterables. With multiple iterables, the callback receives one item from each; iteration normally ends when the shortest input is exhausted, while strict=True rejects unequal lengths.
map(function, iterable, /, *iterables, strict=False)| Name | Type | Description |
|---|---|---|
function | callable | Callable applied to each item, receiving one argument per iterable. |
iterable | iterable | Primary iterable supplying items to transform. |
iterables | iterable, ... | Optional additional iterables consumed in parallel. |
strict | bool | If true, raise ValueError when parallel iterables have different lengths. |
An iterator yielding the function results.
numbers = [1, 2, 3]
factors = [10, 20, 30]
scaled = list(map(lambda number, factor: number * factor, numbers, factors))
print(scaled) # [10, 40, 90]A list materializes the iterator so its mapped results can be reused.
Convert or normalize each value without constructing an intermediate list immediately.
Combine aligned records, keys, or measurements by passing several iterables to one callback.
Validate that parallel inputs contain the same number of items.
map() returns an iterator rather than an eagerly built list. The callback is applied as results are requested, so wrapping it in list() consumes the iterator and materializes the values.
Follow-up: How can laziness affect repeated use? An iterator is consumed during iteration, so create a new map object or store the materialized results if multiple passes are required.
With extra iterables, the callback must accept one argument for each iterable. Items are taken in parallel, and ordinary map() stops as soon as the shortest iterable is exhausted.
Follow-up: How can mismatched lengths be detected? Pass strict=True; Python raises ValueError if any iterable ends before the others.
The function argument is positional-only, and additional iterables are supplied after the primary iterable. The current signature also provides strict=False to control unequal-length handling.
Follow-up: When is itertools.starmap() preferable? Use it when each source item is already an argument tuple that should be unpacked into the function call.
itertools.starmap()filter()generator expressions