Python 程序:向列表追加元素

编写一个程序向列表中追加元素。在这个 Python 编程语言中,我们有多种选择来追加或添加一个元素到列表中,它们是 `append()`、`insert()` 和 `extend()` 函数。本页将通过每个函数的示例展示这三种可能性。

使用 `append()` 函数

在此示例中,我们在预先声明的列表上使用列表的 `append()` 方法。列表的 `append()` 方法将新元素添加到列表的末尾。`append()` 函数的语法是 `list.append(item)`。

numbers = [10, 20, 30, 40, 50]

print("Numeric List Before Appending Item")
print(numbers)

numbers.append(65)

print("Numeric List After Appending First Item")
print(numbers)

value = int(input("Please enter the List Item = "))
numbers.append(value)

print("Numeric List After Appending Second Item")
print(numbers)
Program to Append an Item to a List

使用 `insert()` 函数向列表追加元素的 Python 程序

此程序使用索引函数向列表追加元素。列表的 `insert()` 方法将列表元素插入到指定索引处。`insert()` 函数的语法是 `list.insert(index, item)`。

countries = ["India", "USA", "UK", "Italy"]

print("List Before Appending Item")
print(countries)

countries.insert(3, "Japan")
print("\nList After Appending Japan at 3rd Index Position")
print(countries)

countries.insert(0, "China")
print("\nList After Appending China at 0 Index Position")
print(countries)

countries.insert(6, "France")
print("\nList After Appending France at 6 Index Position")
print(countries)
List Before Appending Item
['India', 'USA', 'UK', 'Italy']

List After Appending Japan at 3rd Index Position
['India', 'USA', 'UK', 'Japan', 'Italy']

List After Appending China at 0 Index Position
['China', 'India', 'USA', 'UK', 'Japan', 'Italy']

List After Appending France at 6 Index Position
['China', 'India', 'USA', 'UK', 'Japan', 'Italy', 'France']

这个 示例 允许输入列表索引和列表值,并使用索引方法添加该新元素。

numbers = [11, 22, 33, 44, 55, 66]

print("Numeric List Before Inserting Item")
print(numbers)


index = int(input("Please enter Index Position = "))
value = int(input("Please enter the List Value = "))

numbers.insert(index, value)

print("Numeric List After Appending Item")
print(numbers)
Numeric List Before Inserting Item
[11, 22, 33, 44, 55, 66]
Please enter Index Position = 4
Please enter the List Value = 111
Numeric List After Appending Item
[11, 22, 33, 44, 111, 55, 66]

使用 `extend()` 方法

列表的 `extend()` 方法将任何可迭代对象(如列表、元组、字符串等)添加到现有列表的末尾。`extend()` 函数的语法是 `list.extend(iterator)`。

countries = ["India", "USA", "UK", "Italy"]

print("List Before Appending Item")
print(countries)

tuple1 = ("Japan", "China", "France")
countries.extend(tuple1)
print("\nList After Appending Tuple using extend")
print(countries)

list1 = [19, 17, 39, 55]
countries.extend(list1)
print("\nList After Appending List sing extend")
print(countries)

countries.extend((11.5, 19.2))
print("\nList After Appending 11.5, 19.2 using extend")
print(countries)
append an item to a list using extend function