元组
元组与列表类似,不同之处在于元组的元素不能修改。
所谓元组的不可变指的是元组所指向的内存中的内容不可变
元组的创建
元组创建只需要在括号中添加元素,并使用逗号隔开即可。
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d" # 不需要括号也可以
print(type(tup3))
>>><class 'tuple'>
创建空元组:
tup_empty = ()
创建一个只包含一个元素的元组:
tup_one = (2,)
tup_int = (2)
print(type(tup_one))
print(type(tup_int))
'''
<class 'tuple'>
<class 'int'>
'''
访问元组
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
'''
tup1[0]: Google
tup2[1:5]: (2, 3, 4, 5)
'''
修改元组
虽然不能修改元组中的元素,但是可以对元组进行连接组合
tup1 = (12,23,45,6.6)
tup2 = ('abc','def')
tup1 = tup1 + tup2
print(tup1)
'''
(12,23,45,6.6,'abc','def')
'''
删除元组
虽说不能修改元组中的元素(包括删除),但是可以删除整个元组
tup = ('Google', 'Runoob', 1997, 2000)
print (tup)
del tup
print ("删除后的元组 tup : ")
print (tup)
'''
('Google', 'Runoob', 1997, 2000)
删除后的元组 tup :
Traceback (most recent call last):
File "F:\Python\Program\test.py", line 6, in <module>
print (tup)
NameError: name 'tup' is not defined
'''
元组内置函数
len(tuple) 计算元组元素个数。
max(tuple) 返回元组中元素最大值。
min(tuple) 返回元组中元素最小值
tuple(iterable) 将可迭代系列转换为元组。