1.元组
-
元组一般用来存储多个数据,使用()
2.创建元组
-
创建空元组
tup1 = ()
print(tup1) # ()
print(type(tup1)) # <class 'tuple'>
-
创建非空元组(元组中只有一个元素,一般要在元素的后面加 , 若不加 , 该数据类型不一定是元组,取决于元素的数据类型)
tup2 = (12)
print(type(tup2)) # <class 'int'>
tup3 = ("hello")
print(type(tup3)) # <class 'str'>
tup4 = (34,)
print(type(tup4)) # <class 'tuple'>
-
元组中的元素可以是不同的数据类型
tup5 = (132, 4.45, "hello", True, False, 87)
print(tup5) # (132, 4, 45, 'hello', True, False, 87)
print(type(tup5)) # <class 'tuple'>
3.元组元素的访问
-
通过下标访问,0下标表示第一个元素,-1表示最后一个元素
tup5 = (132, 4.45, "hello", True, False, 87)
print(tup5[0]) # 132
print(tup5[-1]) # 87
print(tup5[4]) # False
4.元组中的元素不能修改
tup5 = (132, 4.45, "hello", True, False, 87)
tup5[1] = 99 # TypeError: 'tuple' object does not support item assignment
print(tup5)
5.删除元组 del
tup5 = (132, 4.45, "hello", True, False, 87)
del tup5
print(tup5) # NameError: name 'tup5' is not defined. Did you mean: 'tup1'?