Move item inside list?

In Python, how to move an element to a specific index in a list?

+85
python list
Jul 03 '10 at 23:14
source share
4 answers

Use the insert method for the list:

 l = list(...) l.insert(index, item) 

Alternatively, you can use fragment notation:

 l[index:index] = [item] 

If you want to move an element that is already in the list to the specified position, you will need to delete it and insert it into a new position:

 l.insert(newindex, l.pop(oldindex)) 
+133
Jul 03 '10 at 23:15
source share
— -

A slightly shorter solution that only moves the element to the end, not anywhere else:

 l += [l.pop(0)] 

For example:

 >>> l = [1,2,3,4,5] >>> l += [l.pop(0)] >>> l [2, 3, 4, 5, 1] 
+27
Apr 25 '15 at 11:43
source share

If you do not know the position of the element, you may need to find the index first:

 old_index = list1.index(item) 

then move it:

 list1.insert(new_index, list1.pop(old_index)) 

or IMHO a cleaner way:

 try: list1.remove(item) list1.insert(new_index, item) except ValueError: pass 
+14
Nov 26 '15 at 8:14
source share

The solution is very simple, but you need to know the index of the starting position and the index of the new position:

 list1[index1],list1[index2]=list1[index2],list1[index1] 
+1
Jul 01 '16 at 7:39
source share



All Articles