Interview Questions

How do I apply a method to a sequence of objects?

Python Questions and Answers


(Continued from previous question...)

How do I apply a method to a sequence of objects?

Use a list comprehension:

result = [obj.method() for obj in List]

More generically, you can try the following function:

def method_map(objects, method, arguments):
"""method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
nobjects = len(objects)
methods = map(getattr, objects, [method]*nobjects)
return map(apply, methods, [arguments]*nobjects)

(Continued on next question...)

Other Interview Questions