Python 列表 extend() 方法



Python 列表extend()方法用于将可迭代对象的元素添加到另一个列表的末尾。这个可迭代对象可以是有序元素集合(如列表、字符串和元组)或无序元素集合(如集合)。

extend() 方法将可迭代对象中的元素逐个添加到原始列表中。例如,如果我们用字符串 '34' 扩展列表 ['1', '2'];结果列表将是 ['1', '2', '3', '4'],而不是 ['1', '2', '34']。因此,此方法的时间复杂度为 O(n),其中 n 是此可迭代对象的长度。

最终列表的长度将增加添加到原始列表中的元素个数。

语法

以下是 Python 列表extend()方法的语法:

list.extend(seq)

参数

  • seq - 这是要追加的可迭代对象。

返回值

此方法不返回值,但会将内容添加到现有列表中。

示例

以下示例演示了 Python 列表 extend() 方法的用法。

aList = [123, 'xyz', 'zara', 'abc', 123]
bList = [2009, 'manni']
aList.extend(bList)
print("Extended List : ", aList)

运行上述程序后,会产生以下结果:

Extended List :  [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

示例

让我们来看一个演示此方法的示例场景。这里,我们创建了两个包含星期几的列表:['Mon', 'Tue', 'Wed'] 和 ['Thu', 'Fri', 'Sat']。程序的目的是使用 extend() 方法将一个列表的元素添加到另一个列表中,以形成一个包含所有星期几的列表。

list = ['Mon', 'Tue', 'Wed' ]
print("Existing list:\n",list)

# Extend a list
list.extend(['Thu','Fri','Sat'])
print("Extended a list:\n",list)

编译并运行上面的程序,得到以下结果:

Existing list:
['Mon', 'Tue', 'Wed']
Extended a list:
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

示例

在这个例子中,如果我们传入一个元组作为此方法的参数,则结果列表将被元组的元素扩展。

# Creating a list
nums = [1, 2, 3, 4]
# Displaying the list
print('List Before Appending:')
print(nums)
print()
# Extending the list nums
# 5, 6, 7 will be added at the end of the nums
nums.extend((5, 6, 7))
# Displaying the list
print('List After Appending:')
print(nums)

如果我们运行上面的程序,将显示以下结果:

List Before Appending:
[1, 2, 3, 4]
List After Appending:
[1, 2, 3, 4, 5, 6, 7]

示例

如果将字符串作为参数传递给此方法,则其每个字符都将作为单独的元素添加到列表中。

# Creating a list
list1 = ['h', 'i']
# Displaying the list
print('List Before Appending:')
print(list1)
print()
# extending the list list1
# 'h', 'e', 'l', 'l', 'o' will be added at the end of the list1
list1.extend('hello')
# displaying the list
print('List After Appending:')
print(list1)

如果运行上面的程序,您将得到以下结果。

List Before Appending:
['h', 'i']
List After Appending:
['h', 'i', 'h', 'e', 'l', 'l', 'o']
python_lists.htm
广告
© . All rights reserved.