functional programming with map()

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Sun Feb 24 22:30:44 EST 2002


Donnal Walter <donnal at donnal.net> wrote:
: I know that

: map(f,items)

: is equivalent to:

: for x in items:
:     f(x)


map() collects the results of calling f() over all the x in items, so a
closer translation would be:

###
results = []
for x in items:
    results.append(f(x))
###



: But what is the functional equvalent of:

: for x in items:
:     x.f()



Here's one way to do it:

###
map(lambda x: x.f(), items)
###


We need to feed map() a function that does the action 'x.f()'.  If we
don't want to use lambda, we can do something like this:

###
def call_function_f_from_x(x):
    return x.f()

results = map(call_function_f_from_x, items)
###


If you have more questions, please feel free to ask.  Good luck!



More information about the Python-list mailing list