Simple syntax for bringing a list element to the front in python?
PythonPython 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].