In Python, how do I move an item to a definite index in a list?
8 Answers
Use the insert
method of a list:
l = list(...)
l.insert(index, item)
Alternatively, you can use a slice notation:
l[index:index] = [item]
If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:
l.insert(newindex, l.pop(oldindex))
-
36Just keep in mind that moving an item already in a list with the insert/pop method will have different behavior depending if you're moving towards front or back of the list. Moving to the left you insert before the object you've chosen. Moving to the back you insert after the item you've chosen. Check for moving to the end of the list (index error).– MKarasJul 27, 2012 at 10:53
-
How to move multiple elements? Given a list a = [1,2,3,4,5,6,7,8,9], how to transform it to [1,2,[3,4,5],6,7,8,9]? Can this be done in one step or with a list comprehension?– user67416Feb 21, 2013 at 19:04
-
@MKaras I tested this with Python 3.5 and you CAN insert to
last index + 1
without errors. The element is just appended to the list in that case. Nov 25, 2016 at 9:47 -
@user2061057 is correct :) even large indexes will result in things inserted at the end.
a.insert(99999, 1)
In [14]: a
Out[14]: [...., 1]
Aug 27, 2018 at 4:12 -
1For those who are trying to use index -1 to insert the item at the end, you have to use len(l) instead.– ndaOct 19, 2019 at 15:04
A slightly shorter solution, that only moves the item to the end, not anywhere is this:
l += [l.pop(0)]
For example:
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
-
21You might as well use
l.append(l.pop(0))
. It's only marginally longer, but it's much more readable. Jan 11, 2017 at 20:27 -
How might I be able to move it to the start instead?– user13645394Aug 4, 2020 at 21:29
-
1
If you don't know the position of the item, 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:
list1.remove(item)
list1.insert(new_index, item)
-
9I think I'm right to cringe at your
pass
statement... never hide exceptions - the default thing in an example like this should be to provide a cleaner error statement or print statement...raise ValueError(f'Unable to move item to {new_index}')
orprint(f'Moving item to {new_index} failed. List remains unchanged.')
. Maybepass
would be ok if in a function calledtry_to_move_item
or something so that its understood that the operation might fail silently. Nov 8, 2018 at 21:11
A solution very simple, but you have to know the index of the original position and the index of the new position:
list1[index1],list1[index2]=list1[index2],list1[index1]
-
10
I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:
┌──────────┬──────────────────────┐ │ 14.4usec │ x[i:i]=x.pop(j), │ │ 14.5usec │ x[i:i]=[x.pop(j)] │ │ 15.2usec │ x.insert(i,x.pop(j)) │ └──────────┴──────────────────────┘
and here the ones to use if j<=i:
┌──────────┬───────────────────────────┐ │ 14.4usec │ x[i:i]=x[j],;del x[j] │ │ 14.4usec │ x[i:i]=[x[j]];del x[j] │ │ 15.4usec │ x.insert(i,x[j]);del x[j] │ └──────────┴───────────────────────────┘
Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.
I'd prefer to do it in one expression like this:
>>> l = [1,2,3,4,5]
>>> [*l, l.pop(0)]
[2, 3, 4, 5, 1]
-
2
l = list(...) #replace ... with the list contents
if item in l: #Checks if the item to be moved is present in the list
l.remove(item) # Removes the item from the current list if the previous line's conditions are achieved
l.insert(new_index,item) # Adds item to new list
A forwards(left to right) swapping example:
>>> abc = [1,2,3,4,5]
>>> abc.insert(0, abc.pop(len(abc)-1))
[5, 1, 2, 3, 4]