An introductory example to itertools.starmap and an explanation of why it is called “starmap”.

Imagine you have a series of tuples with arguments for a Python 🐍 function.

For example, tuples of base and exponent: [(2, 3), (2, 4), (2, 5)] to represent 2³, 2⁴, 2⁵.

How can you map a function into those arguments?

Use itertools.starmap!

>>> args = [
...     (2, 3),
...     (2, 4),
...     (2, 5),
... ]

>>> from itertools import starmap 
>>> list(starmap(pow, args))
[8, 16, 32]

Why is it called starmap?

I'll show you!

How would you do this if you didn't know about starmap?

You would probably do this by mapping a lambda with *args ("star-args"):

>>> args = [
...     (2, 3),
...     (2, 4),
...     (2, 5),
... ]

>>> list(map(lambda args: pow(*args), args)) 
[8, 16, 32]

Another interesting alternative could be to use zip (with star) to “unzip” the arguments.

Then, you could use a plain map:

>>> args = [
...     (2, 3),
...     (2, 4),
...     (2, 5),
... ]

>>> bases, exponents = zip(*args)
>>> bases
(2, 2, 2)
>>> exponents
(3, 4, 5)
>>> list(map(pow, bases, exponents))
[8, 16, 32]

What alternative do you often use? Will you start using starmap now?

Espero que tenhas aprendido algo novo! Se sim, considera seguir as pisadas dos leitores que me pagaram uma fatia de pizza 🍕. O teu pequeno contributo ajuda-me a manter este projeto grátis e livre de anúncios aborrecidos.

Artigo anterior Próximo artigo

Blog Comments powered by Disqus.