在上节我们学习了python中列表的基础使用,我们本节来对元组进行基础的学习。
列表中的元素是可变的(即可进行增删改),我们将其称为可变序列。
而我们今天要学习的数组,其本身不可增删元素,也不能进行元素的修改,所以元组又称为不可变的列表。
1.元组的创建
变量名 = (元素, ...)
变量名 = tuple((元素, ...))
如:
a = (10, 20, "hello")
print(a)
print(type(a))
输出结果为:
(10, 20, 'hello')
<class 'tuple'>
对于创建a时的(10, 20, "hello")中,括号可以省略,即:
a2 = 10, 20, "hello"
print(a2)
print(type(a2))
(10, 20, 'hello')
<class 'tuple'>
b = tuple((10, 50, "hello"))
print(b)
print(type(b))
(10, 50, 'cnm')
<class 'tuple'>
但注意,下列的创建方式是错误的:
b = tuple(110, 50, 11)
即在使用tuple创建元组时,括号是不可省略的。
另外,创建单个元素的元组时,必须在元素后加上逗号“,”,否则该变量直接指向该元素(即把括号省略了),如:
d1 = ("hello")
d2 = ("hello",)
print(d1)
print(type(d1))
print(d2)
print(type(d2))
输出结果为:
hello
<class 'str'>
('hello',)
<class 'tuple'>
2.元组的遍历
元组的遍历与列表遍历相似:
for 迭代变量 in 元组:
代码块
如:
f = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
for i in f:
print(i, end=" ")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
3.元组的注意事项
元组是不可变序列,其值不能发生变化(确切的说其实是其元素的id(类似于指针)不能发生改变)。如有下面一个元组,如果我们试图改变其内的元素:
e = (10, 20, 50)
print(e)
e[2] = 30
结果为:
(10, 20, 50)
Traceback (most recent call last):
File "test.py", line 3, in <module>
e[2] = 30
TypeError: 'tuple' object does not support item assignment
但,如果其内部的元素是如列表这类进行操作id不会发生改变的,又可以进行更改:
e = (10, [20, 30], 50)
print(e)
e[1].append(40)
print(e)
输出结果为:
(10, [20, 30], 50)
(10, [20, 30, 40], 50)