pythonpython-2.7

How to use map() to call class methods on a list of objects


I am trying to call object.method() on a list of objects.

I have tried this but can't get it to work properly

newList = map(method, objectList)

I get the error method is not defined but I know that is because it is a class method and not a local function.

Is there a way to do this with map(), or a similar built in function? Or will I have to use a generator/list comprehension?

edit Could you also explain the advantages or contrast your solution to using this list comprehension?

newList = [object.method() for object in objectList]

Solution

  • newList = map(method, objectList) would call method(object) on each object in objectlist.

    The way to do this with map would require a lambda function, e.g.:

    map(lambda obj: obj.method(), objectlist)
    

    A list comprehension might be marginally faster, seeing as you wouldn't need a lambda, which has some overhead (discussed a bit here).