python元组的基本用法

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。例如:

testtuple= ("apple", "banana", "cherry")
print(testtuple)

1.访问元组元素

与列表相同,索引从0开始。也可以使用负索引,-1 表示最后一个元素,-2 表示倒数第二个元素,依此类推。

testtuple= ("apple", "banana", "cherry")
print(testtuple[1])
print(testtuple[-2])

输出为:

banana
banana

2.更改元组值

创建元组后,无法更改其值。元组是不可变的,或者也称为恒定的。因此无append,insert方法,修改值也会报错。例如:

testtuple= ("apple", "banana", "cherry")
testtuple[2]="grape"
print(testtuple)

报错如下:

    testtuple[2]="grape"
TypeError: 'tuple' object does not support item assignment

有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。

testtuple1= ("apple", "banana", "cherry")
list1 = list(testtuple1)
list1[1] = "grape"
testtuple1 = tuple(list1)
print(testtuple1)

输出:

('apple', 'grape', 'cherry')

3.删除元组元素

元组是不可更改的,因此无法删除元素,但可以删除整个元组:

testtuple1= ("apple", "banana", "cherry")
del testtuple1[0]

输出:

    del testtuple1[0]
TypeError: 'tuple' object doesn't support item deletion

删除整个元组:

testtuple1= ("apple", "banana", "cherry")
del testtuple1
print(testtuple1)

输出:

    print(testtuple1)
NameError: name 'testtuple1' is not defined
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远不要矫情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值