Article Directory
1. List insertion operation
1. Introduction to List#insert function
The Python list inserts elements by calling the List#insert function, which needs to pass in two parameters,
- The first parameter is the subscript index;
- The second parameter is the element to insert;
The function of this function is to insert a new element before the element specified by the subscript, and the element at the original subscript position is pushed to the back position;
List#insert function prototype:
def insert(self, *args, **kwargs): # real signature unknown
""" Insert object before index. 在索引之前插入对象。"""
pass
2. Code example - list insert element
Code example:
"""
列表 List 常用操作 代码示例
"""
# 定义列表
names = ["Tom", "Jerry", "Jack"]
print(names)
# 插入数据
names.insert(1, "Trump")
print(names)
Results of the :
['Tom', 'Jerry', 'Jack']
['Tom', 'Trump', 'Jerry', 'Jack']
2. List append element operation
1. Introduction to List#append function
The operation of adding elements to the list can be realized by calling the List#append function, and the added elements are directly placed at the end of the list;
- An element can be appended;
- It is also possible to append a list containing multiple elements, but the appended list is treated as one element;
List#append function prototype:
def append(self, *args, **kwargs): # real signature unknown
""" Append object to the end of the list.将对象追加到列表的末尾。 """
pass
2. Code example - adding elements to the list
Code example:
"""
列表 List 常用操作 代码示例
"""
# 定义列表
names = ["Tom", "Jerry", "Jack"]
print(names)
# 插入单个数据
names.append("Trump")
print(names)
# 插入多个数据
names.append(["Joe", "Bob"])
print(names)
Results of the :
['Tom', 'Jerry', 'Jack']
['Tom', 'Jerry', 'Jack', 'Trump']
['Tom', 'Jerry', 'Jack', 'Trump', ['Joe', 'Bob']]