元组定义
python的元组与列表类似,也是容器的一种,不同之处在于元组的元素不能修改。
元组的类型为tuple,用一对()表示,中间用,分隔。
names = ('itcast','itheima','bxg')
print(names)
print(type(names))
('itcast', 'itheima', 'bxg')
<class 'tuple'>
错误的实例
#错误的实例
names = ('itcast')
print(names)
print(type(names))
itcast
<class 'str'>
元组一定要有小括号包裹和逗号分隔。
#正确的实例
names = ('itcast',)
print(names)
print(type(names))
('itcast',)
<class 'tuple'>
访问元组的元素(索引)
#访问元组的元素
names = ('itcast','itheima','bxg')
print(names[1])
itheima
获取索引
#获取索引
names = ('itcast','itheima','bxg')
index = names.index('itheima')
print(index)
1
元组不能添加元素(append())和修改(删除,排序)元素
names = ('itcast','itheima','bxg')
names.append('czxy')
print(names)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-07c8a2d05999> in <module>
1 #添加元素
2 names = ('itcast','itheima','bxg')
----> 3 names.append('czxy')
4 print(names)
AttributeError: 'tuple' object has no attribute 'append'
#修改元素
names = ('itcast','itheima','bxg')
names[1] = 'czxy'
print(names)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-999951aa1874> in <module>
1 #修改元素
2 names = ('itcast','itheima','bxg')
----> 3 names[1] = 'czxy'
4 print(names)
TypeError: 'tuple' object does not support item assignment
元组具有自动组组包和解包功能以及交换功能
#自动组包
names = 'itcast','bxg','itheima'
print(names)
print(type(names))
('itcast', 'bxg', 'itheima')
<class 'tuple'>
#自动解包
names = ('itcast','itheima','bxg')
names1,names2,names3=names
print(names1)
print(names2)
print(names3)
itcast
itheima
bxg
#传统交换做法
a = 10
b = 5
t = a
a = b
b = t
print("a = {},b = {}".format(a,b))
a = 5,b = 10
#元祖交换功能
a = 10
b = 5
a,b = b,a
print("a = {},b = {}".format(a,b))
a = 5,b = 10