元组创建
元组为不可变序列
#一、
#小括号()
t1 = ('hello','mys',98) #小括号可省略
print(t1)
#('hello', 'mys', 98)
k = ('hello')
print(type(k))
#<class 'str'> 当元祖仅有一个元素时,最后一个','不可省略,
k = 'hello',
print(type(k))
#<class 'tuple'>
#二、
#内置函数
t2 = tuple(('hello','mys',98))
print(t2)
#('hello', 'mys', 98)
不可变序列特性
为什么将元组设计成不可变序列:
-
多任务环境下,同时操作对象不需要加锁
-
因此,在程序中尽量使用不可变序列
注意事项:
元祖中存储的是对象的引用
①元祖中不可改变其引用
②若元祖的对象是个可变序列,则次对象的数据可以改变
贴张图理解一下
#一、
#元祖引用不可变
t = ('hello','mys',[654,5642,34])
# t[2] = 'zz'
# print(t)
#TypeError: 'tuple' object does not support item assignment
#二、
#若元祖的元素是可变对象,则起元素的数据可改变
t[2].append('yes')
print(t)
#('hello', 'mys', [654, 5642, 34, 'yes'])
元组遍历
t = ('hello','mys',[654,5642,34])
for i in t:
print(i,end=" ")
#hello mys [654, 5642, 34]