tags:

views:

92

answers:

3

Hi folks,

I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this?

This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N operation could do.

    mylist = sorted(mylist,
                    key=lambda x: x == targetvalue,
                    reverse=True)

Cheers, /YGA

+10  A: 

To bring (for example) the 5th element to the front, use:

mylist.insert(0, mylist.pop(5))
Alex Martelli
+4  A: 

I would go with:

mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
Mike Hordecki
A: 

Note: the following code (and the sample code you offered) will put all matching elements at the front.

x = targetvalue
for i in range(len(mylist)):
    if(mylist[i] == x):
        mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]

For example, if mylist = [1, 2, 3, 4, 3] and x = 3, this will result in [3, 3, 1, 2, 4].

Thomas Weigel