将元素添加到列表
可以使用内置append()
函数将元素添加到List中。通过使用append()
方法一次只能将一个元素添加到列表中,为了使用该append()
方法添加多个元素,使用循环。也可以使用append方法将元组添加到List中,因为元组是不可变的。与集合不同,列表也可以使用append()
方法添加到现有列表中。append()
方法仅适用于在List的末尾添加元素,为了在所需位置添加元素,使用insert()
方法。与append()
只接受一个参数的insert()
方法不同,方法需要两个参数(位置,值)。除了append()
和insert()
方法之外,还有一种添加元素的方法,extend()
,此方法用于在列表末尾同时添加多个元素。
注意 - append()和extend()方法最后只能添加元素
# Python program to demonstrate
# Addition of elements in a List
# Creating a List
List = []
print("Intial blank List: ")
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
# Adding elements to the List
# using Iterator
for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)
# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)
# Addition of List to a List
List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List2.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)








暂无数据