Optimisation problem - in C?

Alex Martelli aleaxit at yahoo.com
Wed Feb 21 00:17:19 CET 2001

"Tim Churches" <tchur at optushome.com.au> wrote in message
news:mailman.982698204.12938.python-list at python.org...
> def makevector(sourcelist,elementlist):
> resultvector = []
> for element in elementlist:
> resultvector.append(sourcelist[element])
> return resultvector
> Questions:
> Can this function (which essentially does the fairly generic operation
> of "fetch the elements of sequence a using the element indexes contained
> in sequence b") be optimised without resorting to a C module?

You can easily make it a *little* bit faster (though using Numeric,
as others suggested, would be better still):

def makevector(sourcelist, elementlist):
    resultvector = [None] * len(elementlist)
    for i in range(len(elementlist)):
        resultvector[i] = sourcelist[elementlist[i]]
    return resultvector

this is a bit faster by avoiding re-allocations of resultvector.


More information about the Python-list mailing list