列表(Lists)就像用其他语言声明的数组一样。列表不一定总是同质的,这使其成为Python中最强大的工具。单个列表可能包含数据类型,例如整数,字符串以及对象。列表是可变的,因此即使在创建后也可以对其进行更改。
Python中的List是有序的,并且有一个确定的计数。列表中的元素按照一定的顺序进行索引,并且列表的索引是在0为第一个索引的情况下完成的。列表中的每个元素在列表中都有其明确的位置,这允许复制列表中的元素,每个元素都有其独特的位置和可信度。
注意:列表是用于保留数据序列并对其进行进一步迭代的有用工具。
创建列表
Python中的列表可以通过将序列放在方括号[]中来创建。与集合不同,list不需要内置函数来创建list。
注意:与集合不同,列表可能包含可变元素。
# Python program to demonstrate # Creation of List # Creating a List List = [] print("Intial blank List: ") print(List) # Creating a List with # the use of a String List = ['GeeksForGeeks'] print("List with the use of String: ") print(List) # Creating a List with # the use of multiple values List = ["Geeks", "For", "Geeks"] print("List containing multiple values: ") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['Geeks', 'For'] , ['Geeks']] print("Multi-Dimensional List: ") print(List)
输出:
Intial blank List: []List with the use of String: ['GeeksForGeeks']List containing multiple values: GeeksGeeksMulti-Dimensional List: [['Geeks', 'For'], ['Geeks']]
创建包含多个不同或重复元素的列表
列表可能包含具有不同位置的重复值,因此,在创建列表时,可以将多个不同或重复的值作为序列传递。
# Creating a List with # the use of Numbers # (Having duplicate values) List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print("List with the use of Numbers: ") print(List) # Creating a List with # mixed type of values # (Having numbers and strings) List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks'] print("List with the use of Mixed Values: ") print(List)
输出:
List with the use of Numbers: [1, 2, 4, 4, 3, 3, 3, 6, 5]List with the use of Mixed Values: [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
向列表中添加元素
使用append()方法
可以使用