如何在Python中将元素添加到列表

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

在本教程中,我们将学习使用Python向列表中添加元素的不同方法。

在Python中向List添加元素的方法

有四种方法可以在Python中将元素添加到列表中。

  • append():将对象追加到列表的末尾。

  • insert():在给定索引之前插入对象。

  • extend():通过添加来自iterable的元素来扩展列表。

  • 列表串联:我们可以使用+运算符来串联多个列表并创建一个新列表。

Python将元素添加到列表示例

我们可以将元素添加到列表的末尾或者任何给定的索引处。
有一些方法可以将元素从可迭代对象添加到列表中。
我们还可以使用+运算符连接多个列表以创建新列表。

1. append()

此函数将元素添加到列表的末尾。

fruits = ["Apple", "Banana"]

# 1. append()
print(f'Current Fruits List {fruits}')

f = input("Please enter a fruit name:\n")
fruits.append(f)

print(f'Updated Fruits List {fruits}')

输出:

Current Fruits List ['Apple', 'Banana']
Please enter a fruit name:
Orange
Updated Fruits List ['Apple', 'Banana', 'Orange']

2. insert()

此函数在列表的给定索引处添加一个元素。
在列表的指定索引处添加元素非常有用。

num_list = [1, 2, 3, 4, 5]

print(f'Current Numbers List {num_list}')

num = int(input("Please enter a number to add to list:\n"))

index = int(input(f'Please enter the index between 0 and {len(num_list) - 1} to add the number:\n'))

num_list.insert(index, num)

print(f'Updated Numbers List {num_list}')

输出:

Current Numbers List [1, 2, 3, 4, 5]
Please enter a number to add to list:
20
Please enter the index between 0 and 4 to add the number:
2
Updated Numbers List [1, 2, 20, 3, 4, 5]

3.extend()

此函数将可迭代元素添加到列表中。
将元素从可迭代对象追加到列表的末尾很有用。

list_num = []
list_num.extend([1, 2])  # extending list elements
print(list_num)
list_num.extend((3, 4))  # extending tuple elements
print(list_num)
list_num.extend("ABC")  # extending string elements
print(list_num)

输出:

[1, 2]
[1, 2, 3, 4]
[1, 2, 3, 4, 'A', 'B', 'C']

4.列表串联

如果必须串联多个列表,可以使用" +"运算符。
这将创建一个新列表,而原始列表将保持不变。

evens = [2, 4, 6]
odds = [1, 3, 5]

nums = odds + evens
print(nums)  # [1, 3, 5, 2, 4, 6]

新列表将包含列表中从左到右的元素。
它类似于Python中的字符串连接。