一、定义:
列表是一种有序、可变的容器,可以包含任意类型的元素。定义一个列表使用的是方括号([]),列表中的元素之间用逗号分隔。
以下是几种常见的列表定义方式:
-
空列表:
my_list = []
-
包含元素的列表:
my_list = [1, 2, 3, 4, 5, 6]
-
列表中嵌套列表:
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
-
列表中包含不同类型的元素:
my_list = [1, 'a', True, [2, 3]]
二、列表常用方法
-
list.append(item): 在列表末尾添加一个元素。
fruits = ['apple', 'banana', 'orange'] fruits.append('grape') print(fruits) # 输出: ['apple', 'banana', 'orange', 'grape']
-
list.extend(iterable): 将可迭代对象中的元素逐个添加到列表末尾。
fruits = ['apple', 'banana', 'orange'] more_fruits = ['grape', 'kiwi'] fruits.extend(more_fruits) print(fruits) # 输出: ['apple', 'banana', 'orange', 'grape', 'kiwi']
-
list.insert(index, item): 在指定索引位置插入一个元素。
fruits = ['apple', 'banana', 'orange'] fruits.insert(1, 'grape') print(fruits) # 输出: ['apple', 'grape', 'banana', 'orange']
-
list.remove(item): 移除列表中第一个匹配的元素。
fruits = ['apple', 'banana', 'orange'] fruits.remove('banana') print(fruits) # 输出: ['apple', 'orange']
-
list.pop(index): 移除并返回指定索引位置的元素,不写索引值则默认为最后一个元素。
fruits = ['apple', 'banana', 'orange'] removed_fruit = fruits.pop(1) print(removed_fruit) # 输出: 'banana' print(fruits) # 输出: ['apple', 'orange'] fruits.pop() # 输出: ['apple']
-
list.index(item): 返回列表中第一个匹配元素的索引。
fruits = ['apple', 'banana', 'orange'] index = fruits.index('banana') print(index) # 输出: 1
-
list.count(item): 返回列表中指定元素的出现次数。
fruits = ['apple', 'banana', 'orange', 'banana'] count = fruits.count('banana') print(count) # 输出: 2
-
list.sort(): 对列表进行原地排序。
fruits = ['apple', 'banana', 'orange'] fruits.sort() print(fruits) # 输出: ['apple', 'banana', 'orange']
-
list.reverse(): 将列表中的元素反转。
fruits = ['apple', 'banana', 'orange'] fruits.reverse() print(fruits) # 输出: ['orange', 'banana', 'apple']
-
list.copy(): 创建并返回一个列表的浅拷贝。
fruits = ['apple', 'banana', 'orange'] fruits_copy = fruits.copy() print(fruits_copy) # 输出: ['apple', 'banana', 'orange']
三、属性
-
len(list): 返回列表中元素的个数。
fruits = ['apple', 'banana', 'orange'] length = len(fruits) print(length) # 输出: 3
-
list.clear(): 清空列表中的所有元素。
fruits = ['apple', 'banana', 'orange'] fruits.clear() print(fruits) # 输出: []
-
list.count(item): 返回列表中指定元素的出现次数。
fruits = ['apple', 'banana', 'orange', 'banana'] count = fruits.count('banana') print(count) # 输出: 2
-
list.index(item, start, end): 返回列表中指定元素在指定范围内的索引。
fruits = ['apple', 'banana', 'orange', 'banana'] index = fruits.index('banana', 1, 3) print(index) # 输出: 3