在 Python 中插入列表的第一个位置 [英] Insert at first position of a list in Python

查看:36
本文介绍了在 Python 中插入列表的第一个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在列表的第一个索引处插入元素?如果我使用 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]

这篇关于在 Python 中插入列表的第一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆