How to Use starmap() to Unpack Tuple Arguments in Python

Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

9 lines
Python 3.9+
from itertools import starmap

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
    results = list(starmap(multiply, pairs))
    print(results)

Output

stdout
[6, 20, 42, 72]

How it works

itertools.starmap works like map, but instead of passing each iterable item as a single argument, it unpacks tuples (or any iterable) into separate positional arguments for the function. This is useful when your data is stored as pairs or groups of arguments. Here, multiply expects two arguments, and starmap unpacks each tuple like (2, 3) into a=2, b=3, calling multiply(2, 3). Because starmap is lazy, we convert the result to a list to see the outputs. For this simple case, a list comprehension like [a * b for a, b in pairs] would also work, but starmap shines when the function is more complex or already defined.

Common mistakes

  • Using `map(multiply, pairs)` instead of `starmap` — that passes the tuple as a single argument and raises a TypeError.
  • Forgetting that `starmap` returns an iterator, so you need `list()` to print the values.
  • Assuming `starmap` works with functions expecting keyword arguments; it only unpacks positional arguments.

Variations

  1. Use a generator expression with tuple unpacking: `(multiply(a, b) for a, b in pairs)`
  2. Use `map` with a lambda that unpacks manually: `list(map(lambda p: multiply(*p), pairs))`

Real-world use cases

  • Applying a mathematical function to coordinate pairs (e.g., multiplying x and y dimensions).
  • Passing pre-built argument tuples to a database insert or API call function.
  • Reducing pairs of start/end indices into a function that processes ranges.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.