In python, how do I move an item to a definite index in a list? Thanks in advance for the reply.
+6
A:
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))
David Zaslavsky
2010-07-03 23:15:44
Thank you! This helped a lot.
Gabriele Cirulli
2010-07-03 23:20:06
@terabytest: glad it was helpful. (FYI, it's preferred to upvote any answer that you find useful)
David Zaslavsky
2010-07-03 23:47:52