元组:
>>> bTuple=(['Monday',1],2,3) >>> bTuple (['Monday', 1], 2, 3) >>> bTuple[0][1] 1 >>> len(bTuple) 3 >>> bTuple[1:] (2, 3)列表元素可以改变
元组元素不可以改变
aList=['AXP','BA','CAT'] >>> aList[1]='Alibaba' >>> print(aList) ['AXP', 'Alibaba', 'CAT'] >>> aTuple=('AXP','BA','CAT') >>> aTuple[1]='Alibaba' Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> aTuple[1]='Alibaba' TypeError: 'tuple' object does not support item assignment >>> aList=[3,5,2,4] >>> aList [3, 5, 2, 4] >>> sorted(aList) [2, 3, 4, 5] >>> aList [3, 5, 2, 4] >>> aList.sort() >>> aList [2, 3, 4, 5] >>> aTuple=(3,5,2,4) >>> sorted(aTuple) [2, 3, 4, 5] >>> aTuple (3, 5, 2, 4) >>> aTuple.sort() Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> aTuple.sort() AttributeError: 'tuple' object has no attribute 'sort'元组用在什么地方:1、在映射类型中作为键使用
2、函数的特殊类型参数
3、作为函数的特殊返回值
def foo(args1,args2='world!'): print(args1,args2) >>> foo('Hello,') Hello, world! >>> foo('Hello,',args2='Python!') Hello, Python! >>> foo(args2='Apple!',args1='Hello,') Hello, Apple! >>> def foo(args1,*argst): print(args1) print(argst) >>> foo('Hello','Wangdachui','Niuyun','Linling') Hello ('Wangdachui', 'Niuyun', 'Linling') >>> def foo(): return 1,2,3 >>> foo() (1, 2, 3)