How do I apply a method to a sequence of objects?
The easiest way to do this is to use a list comprehension or a generator expression:
result = [obj.method() for obj in sequence] result = (obj.method() for obj in sequence)
The former generates a list, the latter an iterator that calls the method as you fetch new items from the iterator. The generator form works especially well if you’re passing the result to another function:
result = function(obj.method() for obj in sequence)
result = map(lambda obj: obj.method(), sequence)
Since this involves an extra function call for each item, it’s a bit slower than the newer alternatives. Note, however, that if you’re calling a function instead of a method, the map approach is faster, since the function object only needs to be looked up once:
result = map(function, sequence)