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
Method #2 : Using insert() + pop() This functionality can also be achieved using the inbuilt functions of python viz. insert() and pop() . The pop function returns the last element and that is inserted at front using the insert function.
The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.
I would go with:
mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
To bring (for example) the 6th element to the front, use:
mylist.insert(0, mylist.pop(5))
(python uses the standard 0 based indexing)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With