Python学习系列《三》【列表】

本文详细介绍了Python中列表的定义、基本操作及常用函数,包括列表的长度获取、元素的添加与删除、替换以及如何通过索引访问元素。此外,还介绍了如何使用负数下标从后往前访问列表元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三、列表       

3.1 列表定义

在Python中,列表是由一系列按特定顺序排列的元素组成,用[]来表示列表,并用英文逗号分隔其中的元素。例如:

>>> print(list);
['h', 'e']
>>> list = [1,2,3,4]
>>> print(list);
[1, 2, 3, 4]
>>> list = ["hello",'world']
>>> print(list);
['hello', 'world']
>>>

同大多数编程语言一样,Python中的列表元素下表也是从0开始计数的,使用[i]访问列表中的元素,例如:

>>> list = ['ni','hao','hello','world']
>>> print(list[0]);
ni
>>> print(list[4]);
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

当超出列表元素索引时,会报出“IndexError: list index out of range”的异常信息。

另外,在访问列表时,负数下标代表从后往前数的元素,例如:

>>> list = ['I','am','very','good'];
>>> print(list[-1])
good
>>> print(list[-2])
very

列表的元素也可以是另外一个数组,例如:

>>> list = ['haha','hehe',[1,2,3]]
>>> print(list)
['haha', 'hehe', [1, 2, 3]]
>>>

 

3.2 列表操作以及常用函数

3.2.1 列表的长度len()

>>> list = ['I','am','very','good'];
>>> print(len(list));
4
>>> print(list[len(list)-1])
good
>>> print(list[-1])
good
>>> print(list[-2])
very

这里需要注意len()函数的用法,是len(list)

3.2.2 列表添加元素

1、在列表末尾添加元素:append()函数

>>> list = ['I','am', 'very','good']
>>> list.append("!");
>>> print(list);
['I', 'am', 'very', 'good', '!']
>>>

2、在列表中随机位置插入新的元素:insert()函数

仍以上面的list为例,在“am”之后的位置添加一个“so”的元素:

>>> print(list);
['I', 'am', 'very', 'good', '!']
>>> list.insert(2,'so')
>>> print(list)
['I', 'am', 'so', 'very', 'good', '!']
>>>

同理,insert()的下标也可以为负数,从后面数往前插入:

>>> list.insert(-1,'haha');
>>> print(list)
['I', 'am', 'so', 'very', 'good', 'haha', '!']
>>>

3.2.3 替换列表中的某个元素的值

直接使用list[i] = newValue,进行复制操作即可:

>>> list = [1,2,3]
>>> list[0]=0
>>> print(list)
[0, 2, 3]
>>>

3.2.4 删除列表中的元素

1、根据索引删除元素:del语句

C:\Users\Administrator>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list = [1,2,3,4]
>>> del list[0]
>>> print(list)
[2, 3, 4]
>>> del list[-1]
>>> print(list)
[2, 3]
>>> del list[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>

2、根据值删除元素:remove()函数

remove函数只删除列表中第一个指定的值:

>>> list = ['one','two','three']
>>> list.remove('two')
>>> print(list)
['one', 'three']
>>> list2 = [1,2,2,3,4]
>>> list2.remove(2)
>>> print(list2)
[1, 2, 3, 4]
>>>

3、pop()函数:

pop()函数删除列表末尾元素,并且返回该元素:

>>> list = [1,2,3,4,5]
>>> temp = list.pop()
>>> print(list)
[1, 2, 3, 4]
>>> print(temp)
5
>>>

pop(i)函数删除第i个位置的元素,并返回该元素:

>>> list = [1,2,3,4,5,6]
>>> temp = list.pop(2)
>>> print(list)
[1, 2, 4, 5, 6]
>>> print(temp)
3
>>>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值