Python map() Function with Examples

Learn Python map() function with examples using custom functions, lambda, built-in functions, multiple iterables, string conversion, list conversion, and map vs list comprehension.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python map() Function with Examples

map() applies a function to each element of an iterable and returns a lazy iterator of results—the standard library’s built-in for “transform every item” without writing an explicit for loop.

python
nums = [1, 2, 3, 4, 5]
squares = map(lambda x: x * x, nums)
print(list(squares))
Output

That prints [1, 4, 9, 16, 25].

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is map() in Python?

map(function, iterable, *iterables) returns an iterator. On each step it calls function with the next value from iterable (or with one value from each parallel iterable). The official model is: apply function to every item of the iterable and yield each return value. Nothing is collected automatically—you either iterate, or wrap in list() when you truly need a list.

For background on for loops, see Python for loop. For anonymous one-liners passed to map, see Python lambda function. When you only need a yes/no scan over mapped flags, any() / all() can be clearer than building a full list—see Python any() and all().


Python map() syntax

text
map(function, iterable[, iterable2, ...]) -> iterator

The first argument must be callable (function, method, class, or lambda). Further arguments must be iterables. With multiple iterables, function must accept that many positional arguments.


Terminology: callable, iterable, and map object

  • Callable: anything you can call with ()—often a function or lambda.
  • Iterable: object that yields values one at a time (list, tuple, string, generator, file lines, etc.).
  • Map object: the iterator map returns; it computes on demand and can only be exhausted once unless you store results in another collection.

People sometimes say “mapping function” or “mapper”; Python’s docs simply call the first argument function.


Simple Python map() example

Cube each number with a small def:

python
def cube(n):
    return n * n * n


numbers = [1, 2, 3, 4, 5]
print(list(map(cube, numbers)))
Output

That prints [1, 8, 27, 64, 125].


Convert map object to list

Because map is lazy, print(map(...)) shows an object address, not the values. Use list(), tuple(), a for loop, or another consumer when you need all items materialized:

python
it = map(str.upper, ["a", "b"])
print(list(it))
Output

That prints ['A', 'B'].


Use map() with built-in functions

Any one-argument callable works. Common choices are type constructors and unary builtins:

python
nums = [-2, -1, 0, 1, 2]
print(list(map(abs, nums)))

words = ["This", "is", "my", "Name"]
print(list(map(len, words)))
Output

That prints [2, 1, 0, 1, 2] then [4, 2, 2, 4].


Use map() with lambda function

When the transform is a single expression, a lambda keeps the call site short:

python
nums = [1, 2, 3, 4, 5]
print(list(map(lambda x: x * x * x, nums)))
Output

That prints [1, 8, 27, 64, 125].


Use map() with a custom function

Named functions improve reuse and stack traces when the logic grows past one line:

python
def label(score):
    return "pass" if score >= 60 else "retry"


marks = [55, 72, 88]
print(list(map(label, marks)))
Output

That prints ['retry', 'pass', 'pass'].


Use map() with multiple iterables

Pass several iterables; each round supplies one argument per iterable. pow is a readable two-argument example:

python
bases = [2, 3, 10]
exponents = [3, 2, 2]
print(list(map(pow, bases, exponents)))
Output

That prints [8, 9, 100].


map() stops at the shortest iterable

When lengths differ, map ends as soon as the shortest input runs out—no error, but longer tails are ignored unless you pad or preprocess lists first.

python
first = [1, 2, 3]
second = [1, 2, 3, 4, 5, 6]
print(list(map(pow, first, second)))
Output

Still [1, 4, 27]; extra 4, 5, 6 never pair with a base.


Convert strings to numbers using map()

int and float are callables—map applies them elementwise:

python
str_nums = ["4", "8", "6", "5", "3"]
int_nums = list(map(int, str_nums))
print(int_nums)
Output

That prints [4, 8, 6, 5, 3]. For numeric types in general, see Python numbers.


Transform strings using map()

Pass bound methods or str methods via map to normalize many strings:

python
words = ["  this", "Is  ", "my", " name"]
stripped = list(map(str.strip, words))
print(stripped)
print(list(map(str.upper, stripped)))
Output

That prints ['this', 'Is', 'my', 'name'] then ['THIS', 'IS', 'MY', 'NAME'].


map() vs list comprehension

Both build transformed sequences. Comprehensions are often clearer for short inline logic; map shines when you already have a named callable or want a lazy iterator without brackets-heavy syntax.

python
nums = [1, 2, 3]
print(list(map(str, nums)))
print([str(n) for n in nums])
Output

Both yield ['1', '2', '3']. For more patterns, see list comprehension.


map() vs filter() vs reduce()

These builtins answer different questions:

  • map(func, it): transform every item (same length stream of outputs).
  • filter(pred, it): keep items where pred is true (subset, possibly shorter). See Python filter function.
  • reduce(func, it) in functools: collapse an iterable to one accumulated value (for example sum via repeated addition)—use only when aggregation is the goal, not simple per-item mapping.
python
from functools import reduce

nums = [1, 2, 3, 4]
print(list(filter(lambda x: x % 2 == 1, nums)))
print(reduce(lambda a, b: a + b, nums))
Output

That prints [1, 3] then 10.


Python map() vs itertools.starmap()

starmap from itertools unpacks each yielded tuple as arguments—useful when your data is already (args...) rows:

python
import itertools

pairs = [(1, 2), (3, 4), (5, 6)]
print(list(itertools.starmap(lambda a, b: a + b, pairs)))
Output

That prints [3, 7, 11]. With map, you would write map(lambda t: t[0] + t[1], pairs) or accept two parallel lists instead.


Common mistakes with map()

  • Forgetting that map returns an iterator and trying to iterate it twice without rebuilding.
  • Passing a lambda or function with the wrong arity when multiple iterables are supplied.
  • Assuming all inputs are consumed when lengths differ—only the shortest path drives the length.
  • Using map only to immediately list(...) a very simple transform where a comprehension might read cleaner to your team.

Python map() quick reference table

Goal Pattern
Transform each item map(func, iterable)
Materialize list(map(...))
Parallel columns map(func, a, b, ...)
Shortest wins multiple iterables of unequal length
Tuple rows unpacked itertools.starmap(func, rows)

Summary

map(function, iterable, *iterables) lazily applies function to each aligned set of inputs and returns a map iterator—materialize with list or consume in a loop. Built-ins, def, and lambda all work as the callable; multiple iterables require matching arity and stop at the shortest sequence. For string digits, map(int, ...) is idiomatic; for style, choose between map and list comprehension on readability. filter and reduce solve selection and folding, not the same default problem as map. itertools.starmap helps when each item is already an argument tuple.


References


Frequently Asked Questions

1. What does Python map() return?

A map iterator that applies the given callable to each item of the iterable(s); wrap with list() or consume in a loop to see all results at once.

2. Can map() take more than one iterable?

Yes; the callable must accept that many positional arguments, and map stops when the shortest iterable is exhausted.

3. Should I use map() or a list comprehension?

Use map with an existing callable for a compact expression; use a list comprehension when the transform is short and readability beats naming a function.

4. What is the difference between map() and starmap()?

map(func, xs, ys) passes parallel elements as separate arguments; starmap(func, pairs) expects an iterable of argument tuples and calls func(*tuple) each time.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …