如何在Python中追加列表中的对象?
列表是Python提供的最常用的数据结构之一。列表是Python中的一种数据结构,它是可变的,具有有序的元素序列。以下是整数值的列表
阅读更多:Python 教程
示例
以下是整数值的列表。
lis= [11,22,33,44,55]
print(lis)
输出
如果执行上述代码片段,则会产生以下输出。
[11, 22, 33, 44, 55]
在本文中,我们将讨论如何向列表中添加对象以及Python中使用append()、insert()和extend()方法添加对象的不同方式。
使用append()方法
在此方法中,我们使用 append() 将对象添加到列表中。 append() 方法将新元素添加到已经存在的列表的末尾。
语法
append() 方法的语法如下。
list_name.append(element)
其中,
- list.name 是列表的名称。
-
append() 是将项目添加到list_name末尾的列表方法。
-
element 是要添加的元素或单个项。
例1
在此示例中,我们使用 append() 方法将对象添加到列表中。在这里,我们将另一个名称添加到名称列表(names_list)中。
names_list = ["Meredith", "Levi", "Wright", "Franklin"]
names_list.append("Kristen")
print(names_list)
输出
上述代码的输出如下。
['Meredith', 'Levi', 'Wright', 'Franklin', 'Kristen']
例2
以下是另一个示例,在其中追加元素到列表中。
numbers_list = [2, 5, 46, 78, 45]
numbers_list.append(54)
print ('The list with the number appended is:',numbers_list)
输出
The list with the number appended is: [2, 5, 46, 78, 45, 54]
使用insert()方法
在此方法中,我们使用insert()向列表中添加对象。 insert() 方法在列表的指定位置添加一个新元素。
语法
insert() 方法的语法如下。
list_name.insert(pos,ele)
其中,
- list.name 是列表的名称。
-
insert() 是将元素插入指定位置的列表方法。
-
pos 是一个整数,指定要添加的元素的位置或索引。
-
ele 是要添加的元素。
例子
在这个例子中,我们使用 insert() 方法在列表的第二个位置上添加一个项目。
lst = ["Bat", "Ball"]
lst.insert(2,"Wicket")
print(lst)
输出
上述代码的输出如下。
['Bat', 'Ball', 'Wicket']
使用extend()函数
在这种方法中,我们将看一下extend()方法,通过将多个列表中的所有元素连接(相加)在一起来合并它们。
语法
insert()方法的语法如下。
list_name.extend(other_list/iterable)
其中,
- list_name 是列表之一的名称。
-
extend() 是将所有内容添加到另一个列表中的方法。
-
iterable 可以是任何可迭代对象,例如另一个列表,即other_list。在这种情况下,other_list是一个将与list_name连接的列表,并且它的内容将单独作为项目逐个添加到list_name的末尾。
例子
在下面的代码中,我们将使用extend()方法连接两个列表。
names_list = ["Meredith", "Levi"]
othernames_list = [ "Franklin", "Wright"]
names_list.extend(othernames_list)
print(names_list)
输出
上述代码的输出如下。
['Meredith', 'Levi', 'Franklin', 'Wright']
极客教程