Python学习之路----元组简介

元组

元组与列表类似,不同之处在于元组的元素不能修改。

所谓元组的不可变指的是元组所指向的内存中的内容不可变

元组的创建

元组创建只需要在括号中添加元素,并使用逗号隔开即可。

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"   #  不需要括号也可以

print(type(tup3))

>>><class 'tuple'>

创建空元组:

tup_empty = ()

创建一个只包含一个元素的元组:

tup_one = (2,)
tup_int = (2)

print(type(tup_one))
print(type(tup_int))

'''
<class 'tuple'>
<class 'int'>
'''
访问元组
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
 
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

'''
tup1[0]:  Google
tup2[1:5]:  (2, 3, 4, 5)
'''
修改元组

虽然不能修改元组中的元素,但是可以对元组进行连接组合

tup1 = (12,23,45,6.6)
tup2 = ('abc','def')

tup1 = tup1 + tup2
print(tup1)

'''
(12,23,45,6.6,'abc','def')
'''
删除元组

虽说不能修改元组中的元素(包括删除),但是可以删除整个元组

tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup
print ("删除后的元组 tup : ")
print (tup)
'''
('Google', 'Runoob', 1997, 2000)
删除后的元组 tup : 
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 6, in <module>
    print (tup)
NameError: name 'tup' is not defined
'''
元组内置函数

len(tuple) 计算元组元素个数。

max(tuple) 返回元组中元素最大值。

min(tuple) 返回元组中元素最小值

tuple(iterable) 将可迭代系列转换为元组。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值