列表(list)用中括号[],元组(tuple)用(),列表可以改变,元组不能改变。除此之外,两者非常类似。
只要用逗号分割了一些值,那么就自动创建了元组。
>>> 1,2,3 (1, 2, 3) >>> (1,2,3) (1, 2, 3) >>> (1,) #只有1个元素的元组,必须要加上逗号,不然就会下面这样 (1,) >>> (1) 1 >>> () #空元组 () >>> 3 * (2+11,)+('c','b') (13, 13, 13, 'c', 'b')
你可以这样赋值
>>> a,b,c = 1,2,3 >>> a 1 >>> b 2 >>> c 3 >>> a,b,c (1, 2, 3) >>> x = (1,2,3,4,5) >>> a,b,c = x #x元组有5个元素,左边只有三个变量不能赋值成功 Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> a,b,c = x ValueError: too many values to unpack (expected 3) >>> a,b,c,d,e = x #5个变量可以赋值成功 >>> a,b,c,d,e (1, 2, 3, 4, 5) >>> *a,b = x #星号*来吸收多余的元素,这时两个变量就能赋值成功 >>> a,b ([1, 2, 3, 4], 5) >>> a,*b,c = x >>> a,b,c (1, [2, 3, 4], 5)
元组的索引和切片与列表的相同
>>> x = (2,3,4,2,1,5) >>> x[1] 3 >>> x[-1] 5 >>> x[:] (2, 3, 4, 2, 1, 5) >>> x[3:] (2, 1, 5) >>> 3 in x #判断3是否是x元组内的元素 True
元组不能修改
>>> x = (2,4,2,1,5,3) >>> x[1] = '3' Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> x[1] = '3' TypeError: 'tuple' object does not support item assignment
元组中的列表元素却可以修改
>>> x = (2,4,'f',1.5,[5,3]) >>> x[-1][1] = 'g' #-1是列表的索引,1是列表中元素3的索引 >>> x (2, 4, 'f', 1.5, [5, 'g'])
删除元组
>>> x = (2,3,4,2,1,5) >>> del x >>> x Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> x NameError: name 'x' is not defined
不能删除元组中的元素
>>> x = (2,3,4,2,1,5) >>> del x[2] Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> del x[2] TypeError: 'tuple' object doesn't support item deletion >>> x (2, 3, 4, 2, 1, 5)
内置函数
tuple函数的功能与list函数基本上一样。
>>> tuple('ab') ('a', 'b')