Python append 列表函数

append 列表用于将一个项添加到旧列表的末尾。这个 Python append 函数可以帮助我们将给定的项(New_item)添加到现有 Old_list 的末尾,append 列表函数的使用方法如下所示。

list.append(New_item)

Python 列表 append 函数示例

首先,我们声明一个包含四个整数值的整数列表,下面的代码会将 50 添加到其末尾。

提示:请参阅 Python 中的 列表函数 文章。

a = [10, 20, 30, 40]

print("Original Items are : ", a)
a.append(50)
print("New Items are       : ", a)
Original Items are :  [10, 20, 30, 40]
New Items are      :  [10, 20, 30, 40, 50]

我们使用此函数将三个整数值添加到整数项中。

a = [10, 20, 30, 40]

print("Original Items are : ", a)
a.append(50)
a.append(60)
a.append(70)
print("New Items are       : ", a)
Original Items are :  [10, 20, 30, 40]
New Items are      :  [10, 20, 30, 40, 50, 60, 70]

append 字符串列表示例

在这个例子中,我们声明了一个字符串元素。接下来,我们使用此方法向其中添加另一个水果。

Fruits = ['Apple', 'Orange', 'Kiwi', 'Grape']

print("Original Items are : ", Fruits)
Fruits.append('Banana')
print("New Items are       : ", Fruits)
Original Items are :  ['Apple', 'Orange', 'Kiwi', 'Grape']
New Items are      :  ['Apple', 'Orange', 'Kiwi', 'Grape', 'Banana']

这个程序与第一个示例相同。但是,我们允许用户输入其长度。接下来,我们使用 For Loop 将这些数字添加到空列表中。

intLi = []
 
number = int(input("Enter the Total Number of Elements: "))
for i in range(1, number + 1):
    value = int(input("Enter the %d Element : " %i))
    intLi.append(value)
    
item = int(input("Enter the New Element : " ))
print("Original Elements are : ", intLi)
intLi.append(item)
print("New Elements are      : ", intLi)
append List Items  Example

在这个 程序 中,我们使用此方法添加单词。

strFruits = []
 
number = int(input("Please enter the Total Number : "))
for i in range(1, number + 1):
    value = input("Please enter the Value of %d Element : " %i)
    strFruits.append(value)
    
item = input("Please enter the New Item to append : " )
print("Original Items are : ", strFruits)
strFruits.append(item)
print("New Items are      : ", strFruits)
Please enter the Total Number : 3
Please enter the Value of 1 Element : Apple
Please enter the Value of 2 Element : Banana
Please enter the Value of 3 Element : Orange
Please enter the New Item to append : Kiwi
Original Items are :  ['Apple', 'Banana', 'Orange']
New Items are      :  ['Apple', 'Banana', 'Orange', 'Kiwi']