views:

59

answers:

1

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
Thank you! This helped a lot.
Gabriele Cirulli
@terabytest: glad it was helpful. (FYI, it's preferred to upvote any answer that you find useful)
David Zaslavsky