元组 与 列表 非常相似,但元组不能 插入 、删除 元素。
创建和访问一个元组
>>> tuple1 = (1, 2, 3, 4, 5, 6, 7)
>>> tuple1
(1, 2, 3, 4, 5, 6, 7)
>>> tuple1[0]
1
>>> tuple1[:5]
(1, 2, 3, 4, 5)
>>> tuple2 = tuple1[:]
>>> tuple2
(1, 2, 3, 4, 5, 6, 7)
元组的核心是逗号,
,不是括号
>>> temp = (1)
>>> temp
1
>>> type(temp)
<class 'int'>
>>> tuple3 = 2, 3, 4, 5
>>> tuple3
(2, 3, 4, 5)
>>> type(tuple3)
<class 'tuple'>
>>> tuple4 = ()
>>> type(tuple4)
<class 'tuple'>
>>> tuple5 = (1,)
>>> type(tuple5)
<class 'tuple'>
>>> tuple6 = 1,
>>> type(tuple6)
<class 'tuple'>
更新元组:切片方法
>>> temp = (1,2,3,5,6)
>>> temp = temp[:3] + (4,) + temp[3:]
>>> temp
(1, 2, 3, 4, 5, 6)
删除元组中的一个元素:切片方法
不举例了
删除整个元组:del()
>>> temp
(1, 2, 3, 4, 5, 6)
>>> del temp
>>> temp
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
temp
NameError: name 'temp' is not defined