Python insert()方法--list

描述

  • insert()方法:用于向列表中指定的索引位置之前插入新的对象,因为是在对应目标之前插入,故此方法无法像append()方法一样将对象添加到列表末尾。

语法

  • 语法格式:list.insert(index, object)

参数

  • index:要插入的列表对象的索引位置。
  • object:插入到列表的对象。

返回值

  • 无返回值

实例

实例如下:

#!/usr/bin/python3

a = ['abc', '2019_11', 'pople']
others = {'name': 'jack'}

a.insert(-1, 'python')   # 在列表末尾之前插入字符串对象(无法添加新的对象到列表末尾)
a.insert(1, others)     # 在索引值为1的对象之前插入others	
print("New list: " + str(a))

输出:

New list: ['abc', {'name': 'jack'}, '2019_11', 'python', 'pople']
原文地址:https://www.cnblogs.com/yuelaoban/p/10608853.html