reordering elements of a list

Travis E. Oliphant oliphant.travis at
Sun Jun 4 03:03:52 CEST 2006

greenflame wrote:
> I am trying to reorder elements of a list and I am stuck as to what
> might be the best way to approach this. I have a (main) list of
> elements and another (ordering) list (which is may shorter,  but not
> longer than the main list) which contains the order in which I want the
> elements of the main list but only as far along as the length of the
> ordering list. This may be confusing so I will try to give an example.
> Suppose the main list is: mainlist = list('qwertyuiop')
> Suppose the ordering list is: orderinglist = [3, 4, 2, 1]
> Then I am looking for a function that will take mainlist and
> orderinglist as arguments and return the following list:
> ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']
> Also by the way the main list is always going to be a list of strings
> and the ordering list will be a list of numbers. Also the largest
> number in orderinglist will always be equal to the length of
> orderinglist. I hope this makes any sense. Thanks for your help.

NumPy ( )  can do this using element-based 
indexing on an array of strings.

Your example:

import numpy
a = numpy.array('qwertyuiop','c')
newlist = a[[2,3,1,0]+range(4,10)].tolist()
print newlist


['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']

But you can also do it with list comprehension pretty easily, so this is 
probably just a shameless plug for NumPy :-)


More information about the Python-list mailing list