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.
Python code
9 linesfrom 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
[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
- Use a generator expression with tuple unpacking: `(multiply(a, b) for a, b in pairs)`
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.