Search code examples
pythonlist

Move an item inside a list?


In Python, how do I move an item to a definite index in a list?


Solution

  • 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))