Simple syntax for bringing a list element to the front in python?

Question:

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)
Asked By: YGA

||

Answers:

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

mylist.insert(0, mylist.pop(5))

(python uses the standard 0 based indexing)

Answered By: Alex Martelli

I would go with:

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

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].

Answered By: Thomas Weigel

This requires just two list operations (no index):

mylist.remove(targetvalue)
mylist.insert(0, targetvalue)

Answered By: proski
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.