在 Python 中插入列表的第一个位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21939652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert at first position of a list in Python
提问by Fr0z3n7
How can I insert an element at the first index of a list ? If I use list.insert(0,elem), do elem modify the content of the first index? Or do I have to create a new list with the first elem and then copy the old list inside this new one?
如何在列表的第一个索引处插入元素?如果我使用list.insert(0,elem),elem会修改第一个索引的内容吗?或者我是否必须使用第一个元素创建一个新列表,然后将旧列表复制到这个新列表中?
采纳答案by michel-slm
Use insert:
使用insert:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
回答by Anov
From the documentation:
从文档:
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)inserts at the front of the list, anda.insert(len(a),x)is equivalent toa.append(x)
list.insert(i, x)
在给定位置插入一个项目。第一个参数是要插入的元素的索引,所以a.insert(0, x)插入到列表的前面,a.insert(len(a),x)等价于a.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

