# 创建元组(用小括号(),元素之间用逗号分隔)
colors = ("红", "绿", "蓝")
numbers = (10, 20, 30, 40)
mixed = (1, "苹果", 3.14, True) # 也能存放不同类型元素
# 访问元组元素(和列表一样通过索引)
print("colors的第一个元素:", colors[0]) # 红
print("numbers的第三个元素:", numbers[2]) # 30
# 查看元组长度
print("mixed的长度:", len(mixed)) # 4
# 遍历元组
print("遍历colors:")
for color in colors:
print(color, end=" ") # 红 绿 蓝
# 尝试修改元组(会报错)
# colors[0] = "黄" # 执行这句会报错:'tuple' object does not support item assignment
# 元组拼接(生成新元组,原元组不变)
t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = t1 + t2
print("\n拼接后的元组:", t3) # (1, 2, 3, 4, 5, 6)
# 单元素元组(必须加逗号,否则会被当作其他类型)
single = (5,) # 这是元组
not_tuple = (5) # 这是整数
print("single的类型:", type(single)) # <class 'tuple'>
print("not_tuple的类型:", type(not_tuple)) # <class 'int'>