itertools.starmap Unpacks Argument Tuples
Unpack argument tuples with itertools.starmap, apply a function to each row, consume a lazy generator, and handle an empty input list.
Code
from itertools import starmap
def power(base: int, exponent: int) -> int:
return base ** exponent
def main() -> None:
pairs = [(2, 3), (4, 5), (6, 7)]
print("powers:", list(starmap(power, pairs)))
# starmap unpacks each tuple into positional arguments.
rows = [("alpha", 3), ("beta", 1), ("gamma", 2)]
labels = starmap(lambda name, count: name * count, rows)
print("labels:", list(labels))
# The input can be lazy; starmap consumes it on demand.
def arguments():
yield ("x", "y")
yield ("z", "w")
joined = starmap(lambda left, right: left + "-" + right, arguments())
print("joined:", list(joined))
print("empty:", list(starmap(power, [])))
if __name__ == "__main__":
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
powers: [8, 1024, 279936]
labels: ['alphaalphaalpha', 'beta', 'gammagamma']
joined: ['x-y', 'z-w']
empty: []How the snippet works
The working surface is the functions power, main and arguments — everything else is wiring.
Using it
Entry signature: def power(base: int, exponent: int) -> int
The demo output is labeled (powers:, labels:, joined:), so every printed line maps back to its originating operation.
Launch the file; main takes over and steps through arguments.
Key statements
def power(base: int, exponent: int) -> int:
return base ** exponent
def arguments():
yield ("x", "y")
yield ("z", "w")
Interactive Tools for This Topic
FAQ
- What does itertools.starmap Unpacks Argument Tuples print when run?
- No setup needed: run the file and look for labeled lines like `powers:`, `labels:`, `joined:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.