元组是python内置的数据结构之一,是一个不可变序列
不可变序列(没有增删改的操作):字符串,元组
可变序列(可执行增删改操作,对象地址不发生改变):列表,字典,集合
元组的创建方式
#使用() #内置函数tuple() #空元组
#元组的创建方式
#第一种 使用()
t=('hello','python',2022)
print(type(t)) #<class 'tuple'>
t2='hello','python',2022
print(type(t2)) #<class 'tuple'> 小括号可以省略
t3=('python',) #如果元组中只有一个元素,逗号不能省略,小括号可以省略
print(type(t3))
#第二种 使用内置函数tuple()
tuple=('hello','python',2022)
print(tuple)
#空元组
t4=()
t5=tuple()
print(t4,t5)
#元组中存储的对象的引用 a)如果元组中对象本身是不可变对象,则不能再引用其他对象 b)如果元组中的对象是可变对象,则可变对象的引用不允许改变,但是数据可以改变
t=(10,[20,30],9)
print(type(t)) #<class 'tuple'>
print(t[0],type(t[0]),id(t[0])) #10 <class 'int'> 2657809427024
print(t[1],type(t[1]),id(t[1])) #[20, 30] <class 'list'> 2657814790272
print(t[2],type(t[2]),id(t[2])) #9 <class 'int'> 2657809426992
#尝试将t[1]修改成100
#t[1]=100 报错,元组是不允许修改元素的
#但[20,30]列表,列表是可变序列,所有可以向列表中添加元素,而列表中的内存地址不变
t[1].append(100) #向列表中添加元素
print(t,id(t[1])) #(10, [20, 30, 100], 9)且列表中的内存地址不发生改变
元组的遍历
元组是可迭代对象
#第一种获取元组的方式,使用索引
t=('hello','python',2022)
print(t[0])
print(t[1])
print(t[2])
#遍历元组
for item in t:
print(item) #hello python 2022