Move an item inside a list?

前端 未结 6 502
-上瘾入骨i
-上瘾入骨i 2020-11-29 01:58

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

6条回答
  •  自闭症患者
    2020-11-29 02:51

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

提交回复
热议问题