元组:Python内置的数据结构之一,是一个不可变序列
不可变序列:字符串、元组(没有增、删、改操作)
可变序列:列表、字典(可以对序列执行增、删、改操作,对象地址不发生改变
元组的创建方式
1、直接小括号 t=('Python','hello',90)
2、使用内置函数tuple() t=tuple(('Python','hello',90))
3、只包含一个元组的元素需要使用逗号和小括号 t=(10 , )
'''第一种,使用()'''
t=('Python','world',90)
print(t)#('Python', 'world', 90)
print(type(t))#<class 'tuple'>
'''第二种,使用内置函数tuple()'''
tu=tuple(('Python','world',90))
print(tu)#('Python', 'world', 90)
print(type(tu))#<class 'tuple'>
'''只包含一个元组的元素需要使用逗号和小括号'''
t2=('hello')
print(type(t2))
t3=("hello",)#<class 'str'>
print(type(t3))#<class 'tuple'>
'''空元组'''
t4=()
t5=tuple()
为什么要将元组设计为不可变序列
1、在多任务环境下,同时操作对象时不需要加锁
2、因此,在程序中尽量使用不可变序列
注意事项:元组中存储的是对象的引用
a)如果元组中对象本身不可对象,则不能再引用其他对象
b)如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
t=(10,[20,30],9)
print(t)#(10, [20, 30], 9)
print(type(t))#<class 'tuple'>
print(t[0],type(t[0]),id(t[0]))#10 <class 'int'> 2538702596688
print(t[1],type(t[1]),id(t[1]))#[20, 30] <class 'list'> 253870880371
print(t[2],type(t[2]),id(t[2]))#9 <class 'int'> 2538702596656
'''尝试将他t[1]修改为100'''
#t[1]=100#TypeError: 'tuple' object does not support item assignment
#元组是不允许修改元素的
'''由于[20,30]是列表,而列表是可变序列,所以可以向列中添加元素,而列表的内存地址不变'''
t[1].append(100)
print(t[1])#[20, 30, 100]
元组的遍历
元组是可迭代对象,所以可以用for……in进行遍历
t=tuple(('Python','hello',90)) for item in t: print(item) |