Python—列表与元组的区别

1. 创建

列表的创建用[ ],而元组的船建用( )

在元组中只有一个元素时,元组创建需要加逗号“,”,逗号是元组的关键

>>>temp1 = (1)
>>>temp2 = (1,)

>>>print( type(temp1) )
<class 'int'>

>>>print( type(temp2) )
<class 'tuple'>

创建空列表和空数组

list1=[]
tuple1=()

2. 访问

元组的访问与数组相似,都可以使用切片访问

3. 更新

列表可以更新,使用append、extend、insert等函数,或者使用切片

但元组是不可更新的,只能创建新的元组,并将其赋值给原变量名

>>> temp=(1,2,3,4,5,6)
>>> temp=temp[:2]+("字符串",)+temp[2:]
>>> temp
(1, 2, '字符串', 3, 4, 5, 6)

元组可以用连接字符“+”

4. 删除

元组是静态的,其内部元素不能更新,也不能删除某个或某些。但是可以删除整个元组

>>> temp=(1,2,3,4,5,6)
>>> del temp
>>> temp
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    temp
NameError: name 'temp' is not defined

注:列表的比较、逻辑、连接和重复操作符,在元组中同样适用。

猜你喜欢

转载自blog.csdn.net/weixin_43217427/article/details/107407309