[Tutor] map() practice

Peter Otten __peter__ at web.de
Sun Oct 21 10:42:40 CEST 2012

```Malcolm Newsome wrote:

> Hello all,
>
> I looked at map() tonight.  I think I have a decent understanding now of
> "how" it works.  However, I'm wondering when it is most commonly used in
> the real world and if you could provide some examples (I like to do a
> lot of web stuff...it that helps with regards to providing a context for
> real world application).

map() is convenient whenever you need to apply an existing function to all items of a list:

A very simple date parser using map()
>>> year, month, date = map(int, "2012-10-21".split("-"))
>>> year, month, date
(2012, 10, 21)

or a list comprehension:
>>> [int(x) for x in "2012-10-21".split("-")]
[2012, 10, 21]

Calculating a sum of absolute values using map()
>>> sum(map(abs, range(-10, 10)))
100

or a generator expression:
>>> sum(abs(x) for x in range(-10, 10))
100

Calculating the dot product of two vectors using map()
>>> x = range(10)
>>> y = range(0, 100, 10)
>>> from operator import mul
>>> sum(map(mul, x, y))
2850

or zip() and a generator expression:
>>> sum(a*b for a, b in zip(x, y))
2850

If you want real-world applications I encourage you to use grep
on the code base that interests you, e. g.:

\$ grep '[^a-zA-Z]map(' /usr/lib/python2.7/*.py | head
/usr/lib/python2.7/argparse.py:            tup = value, ', '.join(map(repr, action.choices))
/usr/lib/python2.7/ast.py:            return tuple(map(_convert, node.elts))
/usr/lib/python2.7/ast.py:            return list(map(_convert, node.elts))
/usr/lib/python2.7/Bastion.py:        print "b._get_.func_defaults =", map(type, b._get_.func_defaults),
/usr/lib/python2.7/CGIHTTPServer.py:        nobody = 1 + max(map(lambda x: x, pwd.getpwall()))
/usr/lib/python2.7/cgi.py:                return map(attrgetter('value'), value)
/usr/lib/python2.7/cgi.py:                return map(attrgetter('value'), value)
/usr/lib/python2.7/cmd.py:                              ", ".join(map(str, nonstrings)))
/usr/lib/python2.7/codecs.py:def make_encoding_map(decoding_map):
/usr/lib/python2.7/code.py:        map(self.write, list)

Note that it is bad style to use map() for its side effects like in the last
match. It does extra work to create a list that consumes memory only to be
thrown away immediatly afterwards:

>>> import sys
>>> lines = ["alpha\n", "beta\n", "gamma\n"]
>>> map(sys.stdout.write, lines) # DON'T DO THIS
alpha
beta
gamma
[None, None, None]

# BETTER
>>> for line in lines:
...     sys.stdout.write(line)
...
alpha
beta
gamma

# EVEN BETTER (in this particular case)
>>> sys.stdout.writelines(lines)
alpha
beta
gamma

PS: In Python 3 map() has become "lazy", i. e. it works like a
generator expression rather than a list comprehension. For some applications
you have to replace map(...) with list(map(...)) to make the code work in
Python 3.

```
{"ft_lang_label":"__label__en","ft_lang_prob":0.6066816,"math_prob":0.7449049,"size":2791,"snap":"2019-26-2019-30","text_gpt3_token_len":805,"char_repetition_ratio":0.1230714,"word_repetition_ratio":0.0,"special_character_ratio":0.3328556,"punctuation_ratio":0.20926517,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9618857,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-06-26T11:00:00Z\",\"WARC-Record-ID\":\"<urn:uuid:e539f1a2-2da9-4088-8bb6-68af75e3ffb1>\",\"Content-Length\":\"5919\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:642299ac-a128-4338-bf3e-50f67cf3ed1f>\",\"WARC-Concurrent-To\":\"<urn:uuid:4a4827d6-5f18-41df-a677-73a29d0692a5>\",\"WARC-IP-Address\":\"188.166.95.178\",\"WARC-Target-URI\":\"https://mail.python.org/pipermail/tutor/2012-October/092386.html\",\"WARC-Payload-Digest\":\"sha1:BVLRKAWWE3GZMHLYZPRGHAKLDGSOIYRH\",\"WARC-Block-Digest\":\"sha1:T6DMWRQNTYAVKEDW3UATBE6OI56LJR7B\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-26/CC-MAIN-2019-26_segments_1560628000266.39_warc_CC-MAIN-20190626094111-20190626120111-00423.warc.gz\"}"}