The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:m:map

map

in-buildt python function (or callable). Part of functional programming features in Python. map() apply an iterable to a function an returns a generator. Use it to process a lot of function calls without using a for loop.

Generally, you can use list comprehension or generator comprehension instead of map() to produce easier-to-read code.

map(function, iterable, …)

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap(). python documentation

example:

>>>def doubler(a):            #make a function 
       return a+a
>>>raw = [1,2,3,4,5,6,7,8]    # use an iterable
>>>result = map(doubler, raw) # apply the function object 
>>>result                     # the result is a generator
<map object at 0x7f6c8a1a2e80>
>>>list(result)               # use it with list()
[2,4,6,8,10,12,14,16]

Also works with functions that take more than one argument, but then you must pass more iterables.

The pow() function takes two arguments

>>>bases = [0,1,2,3]
>>>exponents = [3,2,1,0]
>>>result = map(pow, bases, exponents)
>>>list(result)
[0, 1, 2, 1]

A [lambda] function can be used when you don't need the function definition outside of map. Here, instead of defining a subtract function that calculates the difference of a and b, an anonymous lambda function is used instead:

>>>list(map(lambda a,b: a-b, [100,200,300,400],[1,2,3,4]))
[99, 198, 297, 396]

filter() uses a function that returns only True or False. Use it together with map(). This examples filters out negative numbers and calculates the square root:

>>>import math
>>>list(map(math.sqrt, filter(lambda a: True if a > 0 else False, [9,16,25,36,49,-11])))
[3.0, 4.0, 5.0, 6.0, 7.0]

en/glossary/m/map.txt · Last modified: 2020/10/23 12:10 by horst