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

Python

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

I would go with:

mylist.insert(0, mylist.pop(mylist.index(targetvalue)))

Solution 2 - Python

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

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

(python uses the standard 0 based indexing)

Solution 3 - Python

This requires just two list operations (no index):

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYGAView Question on Stackoverflow
Solution 1 - PythonMike HordeckiView Answer on Stackoverflow
Solution 2 - PythonAlex MartelliView Answer on Stackoverflow
Solution 3 - PythonproskiView Answer on Stackoverflow
Solution 4 - PythonThomas WeigelView Answer on Stackoverflow