📜  Python中的 append() 和 extend()

📅  最后修改于: 2022-05-13 01:55:33.855000             🧑  作者: Mango

Python中的 append() 和 extend()

追加:将其参数作为单个元素添加到列表的末尾。列表的长度增加一。

syntax: 
# Adds an object (a number, a string or a 
# another list) at the end of my_list
my_list.append(object)
my_list = ['geeks', 'for']
my_list.append('geeks')
print my_list

输出:

['geeks', 'for', 'geeks']

注意:列表是一个对象。如果将另一个列表附加到列表上,则参数列表将是列表末尾的单个对象。

my_list = ['geeks', 'for', 'geeks']
another_list = [6, 0, 4, 1]
my_list.append(another_list)
print my_list

输出:

['geeks', 'for', 'geeks', [6, 0, 4, 1]]

extend():迭代其参数并将每个元素添加到列表并扩展列表。列表的长度随着其参数中的元素数量而增加。

syntax: 
# Each element of an iterable gets appended 
# to my_list
my_list.extend(iterable) 
my_list = ['geeks', 'for']
another_list = [6, 0, 4, 1]
my_list.extend(another_list)
print my_list

输出:

['geeks', 'for', 6, 0, 4, 1]

注意:字符串是可迭代的,因此如果您使用字符串扩展列表,您将在迭代字符串时附加每个字符。

my_list = ['geeks', 'for', 6, 0, 4, 1]
my_list.extend('geeks')
print my_list

输出:

['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']

时间复杂度:
Append具有恒定的时间复杂度,即 O(1)。
Extend的时间复杂度为 O(k)。其中 k 是需要添加的列表的长度。