[Tutor] Converting integers into digit sum (Python 3.3.0)
Steven D'Aprano
steve at pearwood.info
Tue Dec 10 11:36:33 CET 2013
On Tue, Dec 10, 2013 at 10:39:34AM +0100, Rafael Knuth wrote:
> I don't understand yet what the "map" function does - can you explain?
> I read the Python 3.3.0 documentation on that topic but I frankly
> didn't really understand it
The "map" function comes from so-called functional programming
languages like Lisp, Scheme and Haskell. The idea, and the name, comes
from the concept of a "mapping" in mathematics. The idea is that you
have some relationship between the things over here and the things over
there, e.g. the places on a map and the places in real life. "Here we
are at the Town Hall, so on the map we must be here..." sort of thing.
So, in mathematics we might have a mapping between (let's say) counting
numbers 1, 2, 3, 4, ... and the even numbers larger than fifty, 52, 54,
56, ... and so on. The mapping function is 50 + 2*x:
x = 1 --> 50 + 2*1 = 52
x = 2 --> 50 + 2*2 = 54
x = 3 --> 50 + 2*3 = 56
x = 4 --> 50 + 2*4 = 58
and so on, where we might read the arrow --> as "maps to".
So the fundamental idea is that we take a series of elements (in the
above case, 1, 2, 3, ...) and a function, apply the function to each
element in turn, and get back a series of transformed elements (52, 54,
56, ...) as the result.
So in Python, we can do this with map. First we define a function to do
the transformation, then pass it to map:
def transform(n):
return 50 + 2*n
result = map(transform, [1, 2, 3, 4, 5, 6])
For short, simple functions, we don't even need to create the function
ahead of time:
result = map(lambda n: 50 + 2*n, [1, 2, 3, 4, 5, 6])
works the same way.
In Python 3, map doesn't actually perform the calculations immediately.
To turn the result into a list, just call the list() function:
result = list(result)
I should emphasis that it's not just mathematical functions where this
is useful. We can use any function that takes a single argument:
def transform(astr):
return "Hello " + astr.strip().title() + "!"
for item in map(transform, [" George ", "SUE\n", "bobby", "MicheLLE", "fred"]):
print(item)
prints:
Hello George!
Hello Sue!
Hello Bobby!
Hello Michelle!
Hello Fred!
or even multiple arguments, in which case you need to pass multiple
data streams:
for item in map(lambda a,b,c: a+b-c, [1000, 2000, 3000], [100, 200, 300], [1, 2, 3]):
print(item)
gives:
1099
2198
3297
--
Steven
More information about the Tutor
mailing list