在Python中将列表插入到第一位置

2024-04-26 11:00:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在列表的第一个索引处插入元素? 如果我使用list.insert(0,elem),elem是否修改第一个索引的内容? 或者我必须用第一个elem创建一个新列表,然后将旧列表复制到这个新列表中?


Tags: 元素内容列表listinsertelem
2条回答

从文档中:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

使用insert

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

相关问题 更多 >