元组:不可更改的list
1.元组的创建
- 空元组的创建
t = ()
print(t) # ()
print(type(t)) # <class 'tuple'>
- 创建只有一个值的元组
#1.
t = (9,)
t2 = (9)
print(t)
print(t2)
print(type(t))
print(type(t2))
'''
(9,)
9
<class 'tuple'>
<class 'int'>
'''
#2.
t3 = 9,
print(t3)
print(type(t3))
'''
(9,)
<class 'tuple'>
'''
- 创建有多个值的元组’
t = (1,2,2,5,4)
print(t)
print(type(t))
'''
(1, 2, 2, 5, 4)
<class 'tuple'>
'''
t2 = 1,2,2,5,4
print(t2)
print(type(t2))
'''
(1, 2, 2, 5, 4)
<class 'tuple'>
'''
# 用其他方式创建
l = [1,2,2,5,4]
t3 = tuple(l)
print(t3)
print(type(t3))
'''
(1, 2, 2, 5, 4)
<class 'tuple'>
'''
元组的特性
- 不能修改,其他和list一样,如访问、切片、相加、相乘、遍历操作
- 切片
t = (1,8,49,84,9,531)
t2 = t[1:5]
print(t)
print(id(t))
print(t2)
print(id(t2)) # id不一样说明没有修改原来的元组
'''
(1, 8, 49, 84, 9, 531)
2227720322696
(8, 49, 84, 9)
2227720835944
'''
- 相加
t1 = (1,2,3,4)
t2 = (5,6,7,8)
print(t1)
print(id(t1))
# 这里相当于传址操作,id变了
t1 = t1 + t2
print(t1)
print(id(t1))
# 不可修改是内容不可修改
t1[0] = 666
'''
(1, 2, 3, 4)
2227721286344
(1, 2, 3, 4, 5, 6, 7, 8)
2227719344760
TypeError: 'tuple' object does not support item assignment
'''
- 遍历
#1.单层遍历
t = (2,59,48,45,65)
for i in t:
print(i, end=" ")
print()
#2.多层遍历
t2 = (("hhh",1),("xxx",2),("qqq",3))
for m,n in t2:
print(m, "-->", n)
'''
2 59 48 45 65
hhh --> 1
xxx --> 2
qqq --> 3
'''
元组的函数
与李斯特基本通用。如len、max、min、count、index
元组变量交换法
a = 666
b = 777
a,b = b,a
print(a) #777
print(b) #666