用户登录
用户注册

分享至

在 Python 中插入列表的第一个位置

  • 作者: 南海华神
  • 来源: 51数据库
  • 2022-10-21

问题描述

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

How can I insert an element at the first index of a list? If I use list.insert(0, elem), does 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?

推荐答案

使用insert:

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

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

In [3]: ls
Out[3]: ['new', 1, 2, 3]
软件
前端设计
程序设计
Java相关