The Artima Developer Community
Sponsored Link

Python Buzz Forum
Why zip when you can map?

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Thomas Guest

Posts: 236
Nickname: tag
Registered: Nov, 2004

Thomas Guest likes dynamic languages.
Why zip when you can map? Posted: Dec 16, 2014 3:46 PM
Reply to this message Reply

This post originated from an RSS feed registered with Python Buzz by Thomas Guest.
Original Post: Why zip when you can map?
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
Latest Python Buzz Posts
Latest Python Buzz Posts by Thomas Guest
Latest Posts From Word Aligned: Category Python

Advertisement

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))))
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))
...

Read: Why zip when you can map?

Topic: Anatomy of a Christmas Stocking Previous Topic   Next Topic Topic: Python averages

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use