我该如何在列表的第一个索引处插入元素?
如果我使用list.insert(0, elem)
,那么elem
是否会修改第一个索引的内容?
还是我必须创建一个包含第一个元素的新列表,然后将旧列表复制到这个新列表中?
使用insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
根据文档:
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