一、元组的创建
# 1. 元组的创建 # 1.1 带括号(推荐) t1 = ('a','b','c',1,2,3) print(type(t1)) # 输出:<class 'tuple'> # 1.2 不带括号 t2 = 'a','b','c',1,2,3 print(type(t2)) # 输出:<class 'tuple'>
二、获取元组数据
# 2. 获取元组数据(同列表一样) # 2.1 正序索引 print(t1[5]) # 输出:3 # 2.2 倒序索引 print(t1[-1]) # 输出:3 # 2.3 范围取值(左闭右开) print(t1[1:3]) # 输出:('b', 'c') # 2.4 成员运算符:in,not in print('b' in t1) # True
三、元组在创建后不可更改
# 3. 元组在创建后不可更改 # t1[0] = 2 # 报错:TypeError: 'tuple' object does not support item assignment # append,insert,pop,update等函数都不支持
四、若元组中包含列表,则列表的内容是可被更改的
# 4. 若元组中包含列表,则列表的内容是可以被更改的 t3 = (['张三', 18], ['李四', 20]) item = t3[0] item[0] = '王五' print(t3) # 输出:(['王五', 18], ['李四', 20])
五、元组运算符
# 5. 元组运算符(是新建了一个元组,和之前的无关) t4 = (1, 2, 3) + (4, 5, 6) print(t4) # 输出:(1, 2, 3, 4, 5, 6) t5 = ('see', 'you') * 2 # 输出:('see', 'you', 'see', 'you') print(t5) # 5.1 元组运算符同样适用于列表,但是不可混合使用 t6 = [1, 2, 3] + [4, 5, 6] print(t6) # 输出:[1, 2, 3, 4, 5, 6] # t7 = [1, 2, 3] + [4, 5, 6] + (7, 8, 9) # 报错:TypeError: can only concatenate list (not "tuple") to list
六、当元组中只有一个元素
# 6. 当元组中只有一个元素时,需要在元素后面加,号,这样才能说明这是一个元组 t6 = ('see',) * 2 print(t6) # 输出:('see', 'see')