- 有序
- 可重复
- 不可更改
定义
符号使用()
元组的创建
空元组的创建
单元素元组的创建,需要在单元素后面添加逗号
tp=()
print(type(tp))
tp=("abc")
print(type(tp))
tp=("abc",)
print(type(tp))
'''
<class 'tuple'>
<class 'str'>
<class 'tuple'>
'''
多元素元组的创建,包含多种数据类型
常见操作
(1)拼接
tp1 = (1, 3, ["a", "b"])
tp2 = ("gh", "123")
tp3 = tp1 + tp2
print(tp3)
'''
(1, 3, ['a', 'b'], 'gh', '123')
'''
(2)重复
tp2 = ("gh", "123")
print(tp2 * 3)
'''
('gh', '123', 'gh', '123', 'gh', '123')
'''
(3)索引(偏移) ,切片
tp1 = (1, 3, ["a", "b"])
tp2 = ("gh", "123")
tp3 = tp1 + tp2
print(tp3)
print(tp2 * 3)
print(tp1[2])
print(tp1[0:1])
print(tp3[1:3])
'''
(1, 3, ['a', 'b'], 'gh', '123')
('gh', '123', 'gh', '123', 'gh', '123')
['a', 'b']
(1,)
(3, ['a', 'b'])
'''
元组的元素不可变(元组中的列表元素可以改变)
tp3 =(1, 3, ['a', 'b'], 'gh', '123')
tp3[2][0] = "abcc"
print(tp3)
'''
(1, 3, ['abcc', 'b'], 'gh', '123')
'''
(4)增删改查
查
-
索引查
index()
tp=(1,2,3,"a","b",["aa","bb","cc","dd"]) print(tp.index("a")) ''' 3 '''
-
切片查
增
不能
删
不能删除某个元素,但可以删除整个:
del tp
print(tp)
'''
Traceback (most recent call last):
File "D:/pycharm_test/day03/03yuanzu.py", line 24, in <module>
print(tp)
NameError: name 'tp' is not defined
'''
最大值
tp = ("a", "b", "c")
print(max(tp), min(tp))
'''
c a
'''
遍历
元素遍历
for i in tp:
print(i)
'''
a
b
c
'''
索引遍历
for i in range(len(tp)):
print(tp[i])
'''
a
b
c
'''
枚举遍历enumerate
for i in enumerate(tp):
print(i)
'''
(0, 'a')
(1, 'b')
(2, 'c')
'''