Python入门第八章---元组

元组() 是不可变序列,操作后对象地址发生改变
不可变序列:字符串、元组(没有增删改的操作)

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]))

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值