Simple syntax for bringing a list element to the front in python? [duplicate]
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
Solution 1:
I would go with:
mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
Solution 2:
To bring (for example) the 6th element to the front, use:
mylist.insert(0, mylist.pop(5))
(python uses the standard 0 based indexing)