Python列表append()方法

时间:2020-02-23 14:42:53  来源:igfitidea点击:

Python列表的append()方法将元素添加到列表的末尾。

Python列表append()语法

append()方法将单个项目添加到现有列表中。
原始列表长度增加了1。
这是最流行的列表方法之一。

append()方法的语法为:

list.append(element)

append()方法采用一个参数,该参数将附加到列表的末尾。
Python列表是可变的。

元素可以是数字,字符串,对象,列表等。
我们可以在列表中存储不同类型的元素。

列出append()返回值

列表append()方法不返回任何内容。
您也可以说append()方法返回"无"。

Python列表append()示例

让我们看一个简单的示例,将一个项目添加到列表的末尾。

vowels = ['a', 'e', 'i']

print(f'Original List is {vowels}')
vowels.append('o')
vowels.append('u')

print(f'Modified List is {vowels}')

输出:

Original List is ['a', 'e', 'i']
Modified List is ['a', 'e', 'i', 'o', 'u']

将列表追加到另一个列表

如果我们将列表传递给append()方法,则它将作为单个项添加到列表的末尾。

list_numbers = [1, 2, 3]

list_primes = [2, 3, 5, 7]

list_numbers.append(list_primes)

print(f'List after appending another list {list_numbers}')

输出:

List after appending another list [1, 2, 3, [2, 3, 5, 7]]

提示:如果要将列表的元素追加到另一个列表,请使用列表extend()方法。

list_numbers_odd = [1, 3, 5]

list_numbers_even = [2, 4, 6, 8]

list_numbers_odd.extend(list_numbers_even)

print(f'List after extending from another list {list_numbers_odd}')

输出:

List after extending from another list [1, 3, 5, 2, 4, 6, 8]