7.元组

元组可以理解为不可修改的列表。元组使用 () 定义,而非 [].
tup = (1,2,3)
# 当元组中只包含一个元素,应该加,.否则圆括号会被当作运算符使用
tup = (1)
print(type(tup)) # <class 'int'>
tup = (1,)
print(type(tup)) # <class 'tuple'>

元组操作

元组除了不可以修改,可以像列表一样,通过索引访问,截取,遍历
tup = (1,2,3,4)
print(tup[0])
print(tup[0:-1])
for item in tup:
print(item)
删除元组:
# 元组不可以修改,但是可以通过del删除整个元组
tup = (1,2,3,4)
del tup
print(tup)
'''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'tup' is not defined
'''

元组的函数

len(tup)
max(tup)
min(tup)
# 将可迭代系列转换为元组
tuple(iterable)