Skip to content

六、元组tuple

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号 (),列表使用方括号 []

1、创建元组

1、方式一:括号创建

python
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
print(type(tup1))		#<class 'tuple'>
print(type(tup2))		#<class 'tuple'>

2、方式二:逗号创建

python
tup3 = "a", "b", "c", "d"   #  不需要括号也可以
print(type(tup3))		#<class 'tuple'>

注意:元组中只包含一个元素时,需要在元素后面添加逗号 , ,否则括号会被当作运算符使用

python
tup1 = (50)
print(type(tup1))     # 不加逗号,类型为整型
#<class 'int'>

tup2 = (50,)
print(type(tup2))     # 加上逗号,类型为元组
#<class 'tuple'>

2、访问元组

元组可以使用下标索引来访问元组中的值

python
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
 
print ("tup1[0]: ", tup1[0])    		#Gooogle
print ("tup2[1:5]: ", tup2[1:5])		#(2,3,4,5)

3、修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合

python
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
 
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
 
# 创建一个新的元组
tup3 = tup1 + tup2
print (tup3)		#(12, 34.56, 'abc', 'xyz')

4、删除元组

元组中的元素值是不允许删除的,但我们可以使用del语句删除整个元组

python
tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup
print (tup)
#Traceback (most recent call last):
#  File "test.py", line 8, in <module>
#   print (tup)
#NameError: name 'tup' is not defined

5、元组运算符

元组之间可以使用 +、**+=**和 ***** 号进行运算

这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式结果描述
len((1, 2, 3))3计算元素个数
a = (1, 2, 3)
b = (4, 5, 6)
c = a+b
c (1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 5, 6)连接,c 就是一个新的元组,它包含了 a 和 b 中的所有元素。
a = (1, 2, 3)
b = (4, 5, 6)
a += b
a (1, 2, 3, 4, 5, 6)`
(1, 2, 3, 4, 5, 6)连接,a 就变成了一个新的元组,它包含了 a 和 b 中的所有元素。
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')复制
3 in (1, 2, 3)True元素是否存在
for x in (1, 2, 3):
print (x, end=" ")
1 2 3迭代

7、元组索引截取

python
元组[起始坐标,结束坐标]		#不包含结束坐标

8、内置函数

Python元组包含了以下内置函数

方法描述
len(tuple) 计算元组元素个数。
max(tuple) 返回元组中元素最大值。
min(tuple)返回元组中元素最小值。
tuple(iterable) 将可迭代系列转换为元组。