元组() 是不可变序列,操作后对象地址发生改变
不可变序列:字符串、元组(没有增删改的操作)
s='hello'
print(s,id(s)) #hello 2431609100528
s=s+'world'
print(s,id(s)) #helloworld 2431610264048
可变序列:列表、字典(可以对序列执行增删改操作,对象地址不发生更改)
lst=[1,2,3]
print(id(lst)) #2431610158592
lst.append(4)
print(id(lst)) #2431610158592
元组的创建方式
直接小括号 元组名=(元素,元素) 小括号可省略
t1=('hello','world',97)
print(t1,type(t1))
t2='hello','world',97
print(t2,type(t2))
使用内置函数tuple() 元组名=tuple((元素,元素))
t3=tuple(('hello','world',97))
print(t3,type(t3))
只包含一个元组的元素需要使用逗号和小括号 元组名=(元素,)
t4=(90) #否则是int类型
print(t4,type(t4)) #90 <class 'int'>
t5=(90,)
print(t5,type(t5)) #(90,) <class 'tuple'>
空元组的创建方式
t6=()
t7=tuple()
print('空元组',t6,t7) #空元组 () ()
元组的遍历
元素个数已知用索引遍历
元素个数未知:
for item in t :
print(item)
例:
t8=('张三',976,'sfuh')
#元素个数已知
print(t8[0])
print(t8[1])
print(t8[2])
#元素个数未知
for item in t8:
print(item)
运行结果:
元组设计成不可变序列的原因
在多任务环境下,同时操作对象时不需要加锁,因此在程序中尽量使用不可变序列
元组中存储的是对象的引用
如果元组中对象本身是不可变对象,则不能再引用其他对象
如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
t=(10,[20,30],40)
print(t,id(t))
print(type(t))
print(t[0],type(t[0]),id(t[0]))
print(t[1],type(t[1]),id(t[1]))
print(t[2],type(t[2]),id(t[2]))
#尝试将t[1]修改成100
print(id(100))
# t[1]=100 #TypeError: 'tuple' object does not support item assignment
#由于t[1]=[20,30],而列表是可变序列,所以可以向列中添加元素,而列表的内存地址不变
t[1].append(100)
print(t,id(t),id(t[1]))
运行结果: