99

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) 
3
  • Your original code is very clear. Also, timsort (Python's internal sorting algorithm) works especially fast with long runs, such as yours ([False, False, False, False, ..., False, True, False, False ... False ]) Commented Nov 29, 2018 at 12:14
  • @jpp This question should not have been closed. It is a meaningfully special case of the linked "duplicate" question which is a lot more general. Commented Jan 6, 2023 at 17:33
  • @Asclepius, sure - reopened. Commented Jan 7, 2023 at 8:03

4 Answers 4

186

I would go with:

mylist.insert(0, mylist.pop(mylist.index(targetvalue))) 
Sign up to request clarification or add additional context in comments.

1 Comment

I combined Mike's answer and Alex's (below): "mylist.insert(0, mylist.pop(mylist.index(mylist[index_in_list])))" because I was working with tuples in the list and Alex's was giving me an error.
46

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

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

(python uses the standard 0 based indexing)

2 Comments

and if we want to move an element called "hello!" and not knowing the index?
@UlfGjerdingen Use index = mylist.index(targetvalue)
22

This requires just two list operations (no index): mylist.remove(targetvalue) mylist.insert(0, targetvalue)

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.