Why zip when you can map?

2014-12-16Comments

Why zip? when you can map?

You’ve got a couple of parallel lists you’d like to combine and output, a line for each pair. Here’s one way to do it: use zip to do the combining.

>>> times = [42.12, 42.28, 42.34, 42.40, 42.45]
>>> names = ['Hickman', 'Guest', 'Burns', 'Williams']
>>> fmt = '{:20} {:.2f}'.format
>>> print('\n'.join(fmt(n, t) for n, t in zip(names, times)))
Hickman              42.12
Guest                42.28
Burns                42.34
Williams             42.40

Slightly more succinctly:

>>> print('\n'.join(fmt(*nt) for nt in zip(names, times)))
...

If you look at the generator expression passed into str.join, you can see we’re just mapping fmt to the zipped names and times lists.

Well, sort of.

>>> print('\n'.join(map(fmt, zip(names, times))))
Traceback (most recent call last):
...
IndexError: tuple index out of range

To fix this, we could use itertools.starmap which effectively unpacks the zipped pairs.

>>> from itertools import starmap
>>> print('\n'.join(starmap(fmt, zip(names, times))))
Hickman              42.12
Guest                42.28
Burns                42.34
Williams             42.40

This latest version looks clean enough but there’s something odd about zipping two lists together only to unpack the resulting 2-tuples for consumption by the format function.

Don’t forget, map happily accepts more than one sequence! There’s no need to zip after all.

Don’t zip, map!
>>> print('\n'.join(map(fmt, names, times)))
...