元组

tuple 和 list 非常类似,但是 tuple 一旦初始化就不能修改(只读的!)

1.元组的定义:()

cls= ('Michael', 'Bob', 'Tracy')

2.元组元素的访问:下标法

cls= ('Michael', 'Bob', 'Tracy')
print ("cls[0]: ", cls[0])
输出结果:cls[0]: Michael

3.cls[0] = 'lisi' 是错误的操作

#TypeError: 'tuple' object does not support item assignment

#元组没有insert、append、pop()等方法。

4.如何定义一个空元组 

t = ()

5.如何定义一个只有一个元素的元组

t = (1,)

注意:必须要有逗号, 否则定义的就不是元组而是 一个整数!

6.元组的优点:

因为 tuple 不可变,所以代码更安全

应用场景: 函数传参的时候,如果不希望传入的参数被 函数修改则选择传递元组

元组内置函数

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

序号方法及描述实例
1 len(tuple)
计算元组元素个数。
>>> tuple1 = ('Google', 'Runoob', 'Taobao')
>>> len(tuple1)
3
>>>
2 max(tuple)
返回元组中元素最大值。
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
>>>
3 min(tuple)
返回元组中元素最小值。
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
>>>
4 tuple(iterable)
将可迭代系列转换为元组。
>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
posted @ 2020-04-22 10:31  独剑飞行天下  阅读(203)  评论(0)    收藏  举报