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)

In older Python versions, you can use map together with a lambda callback:

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)

CATEGORY: programming

 

A Django site. this page was rendered by a django application in 0.03s 2008-10-13 00:31:08.584532. hosted by webfaction.