列表
一、创建列表
可以用[ ]来创建一个列表,列表中的元素之间使用逗号分隔。
示例:创建列表list = [‘hello’, ‘金融’, ‘理财’, 123]
>>> list = ['hello', '金融', '理财', 123]
>>> type(list)
<class 'list'>
>>> list
['hello', '金融', '理财', 123]
二、获取元素
可以使用索引获取列表中的元素,索引从0开始。
示例:获取列表中的第三个元素,在获取最后一个元素。
>>> list = ['hello', '金融', '理财', 123]
>>> list[2]
理财
>>> list[-1]
123
三、添加元素
可以通过append()、extend()、insert()方法为列表添加元素。
- append():在列表的最后位置添加、并且每次只能添加一个元素。
- extend():在列表最后位置添加,一次可以添加多个元素。
- insert():在列表的特定位置添加元素
示例:
- 使用append()方法在list的末尾添加元素selenium.
- 使用extend()方法在list的末尾添加[‘test’, ‘name’]
- 使用insert()方法在list下标为4的位置添加元素insert
>>> list = ['hello', '金融', '理财', 123]
>>> list.append('selenium')
>>> list
['hello', '金融', '理财', 123, 'selenium']
>>>
>>> list.extend(['test', 'name'])
>>> list
['hello', '金融', '理财', 123, 'selenium', 'test', 'name']
>>>
>>> list.insert(4,'insert')
>>> list
['hello', '金融', '理财', 123, 'insert', 'selenium', 'test', 'name']
四、删除元素
可以使用remove(name)、del list[index]、pop()方法删除列表中的元素。
- remove(name):移除指定元素
- del list[index]:移除索引为index的元素
- pop():移除最后一个元素,并且可以将最后一个元素返回
示例:
- 使用remove(name)方法移除list中的‘保险’元素
- 使用del list[index]方法移除下标为2的元素
- 使用pop()方法移除list的最后一个元素,并将最后一个元素返回
>>> list = ['hello', '金融', '理财', 123]
>>> list.remove("金融")
>>> list
['hello', '理财', 123]
>>>
>>> del list[2]
>>> list
['hello', '理财']
>>>
>>> temp = list.pop()
>>> temp
'理财'
>>> list
['hello']
>>>