# [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[2], 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.

```