037、Python 元组定义与使用

本文介绍了Python中的元组,包括元组的定义(不可变容器),操作如创建、重复、成员运算、合并、索引、切片,以及元组的限制(不支持修改、删除和append方法)。

定义:

元组(Tuple):不可变的容器。

元组与列表的主要区别在于元组的元素不能被修改,即元组是不可变的,而列表是可变的。

元组使用圆括号(())表示。

使用:

"""
example037 - Python 元组定义与使用

Author: 不在同一频道上的呆子
Date: 2024/1/28
"""
# 创建
colors = ('red',)  # 创建单个元组需要在后面加个逗号,否则会默认为普通数据
colors1 = ('red', 'yellow', 'blue')
print(colors1)

# 重复运算
print(colors1 * 2)

# 成员运算
print('red' in colors1)
print('purple' in colors1)

# 合并运算
colors2 = ('green', 'purple')
colors3 = colors1 + colors2
print(colors3)

# 索引和切片
print(colors3[4], colors[-1])

# TypeError:'tuple' object does not support item assignment
# colors3[4] = 'pink'

print(colors3[1:4])
print(colors3[1:4:2])
print(colors3[::-1])

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

print(colors3.index('red'))
print(colors3.count('red'))

# AttributeError: 'tuple' object has no attribute 'append'
# colors3.append('pink')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序猿游也

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

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

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

打赏作者

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

抵扣说明:

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

余额充值