列表是继变量之后的又一种数据类型,只是列表这种存储数据的语法类型比较复杂,但是列表的存在能帮助python存储更加复杂,相关数据,大大提高python处理复杂数据的能力。
列表是一种可变数据类型,有自己的语法规则,通过对python的操作我们可以对复杂数据进行丰富的操作,得到更加精确的数据结果。
Python 中列表是一种可变的序列数据类型,它提供了很多方便的内置函数和方法。以下是一些常用的列表方法以及它们的举例:
1.append():在列表的末尾添加元素。
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits)
输出结果:
['apple', 'banana', 'cherry', 'orange']
2.extend():在列表的末尾添加多个元素。
fruits = ['apple', 'banana', 'cherry']
fruits.extend(['orange', 'mango', 'grapes'])
print(fruits)
输出结果:
['apple', 'banana', 'cherry', 'orange', 'mango', 'grapes']
3.insert():在指定位置插入元素。
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'orange')
print(fruits)
输出结果:
['apple', 'orange', 'banana', 'cherry']
4.remove():删除列表中的指定元素。
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)
输出结果:
['apple', 'cherry']
5.pop():删除列表中指定位置的元素,并返回该元素。
fruits = ['apple', 'banana', 'cherry']
removed_fruit = fruits.pop(1)
print(fruits)
print(removed_fruit)
输出结果:
['apple', 'cherry']
banana
6.count():返回列表中指定元素的数量。
fruits = ['apple', 'banana', 'cherry', 'apple']
count = fruits.count('apple')
print(count)
输出结果:2
详细教程参考: