Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 646
10 revs, 7 users 53% Avatar asked Jun 18 '09 18:06

10 revs, 7 users 53%


People also ask

How do you move an element to the front of a list in Python?

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.

How do you repeat the same value in a list Python?

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.


2 Answers

I would go with:

mylist.insert(0, mylist.pop(mylist.index(targetvalue))) 
like image 156
Mike Hordecki Avatar answered Oct 06 '22 00:10

Mike Hordecki


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

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

(python uses the standard 0 based indexing)

like image 27
Alex Martelli Avatar answered Oct 06 '22 00:10

Alex Martelli