列表和元组,都是一个可以放置任意数据类型的有序集合,大多数编程语言(例如Java,C#)中,结合的数据类型必须一致l=[1,2,"hello","world"] #列表中包含int和string类型的元素print(l)tup=(1,2,"hello") #元组中包含int和string类型的元素print(tup)
列表是动态的,长度大小不固定,可以随意增加,删除和改变元素l=[1,2,"hello","world"] #列表中包含int和string类型的元素print(l)tup=(1,2,"hello") #元组中包含int和string类型的元素print(tup)l[2]="88"print(list)tup[2]="77"Traceback (most recent call last): File "/Users/guohu/Pycharm/PythonDemo/list/main.py", line 14, in <module> tup[2]="77" ~~~~~^^^TypeError: 'set' object does not support item assignment
如果对元组做任何改变,需要重新开辟一个新的内存,创建新的元组l=[1,2,"hello","world"] #列表中包含int和string类型的元素print(l)tup=(1,2,"hello") #元组中包含int和string类型的元素print(tup)l[2]="88"print(l)new_tup=tup + (5,)print(new_tup)
Python中的列表和元组都支持负数索引,-1表示最后一个元素,-2表示倒数第二个元素l=[1,2,"hello","world"] #列表中包含int和string类型的元素print(l[-1])tup=(1,2,"hello") #元组中包含int和string类型的元素print(tup[-1])
l=[1,2,"hello","world"] print(l[1:3]) #返回列表中索引从1到2的子列表tup=(1,2,"hello") print(tup[1:3]) #返回元组中索引从1到2的子元组
l=[1,2,"hello","world"]tup=(1,2,"hello")print(tuple(l))print(list(tup))
初始化一个相同元素的列表和元组所需的时间如下,元组的速度比列表快5倍(base) guohu@guohudeMacBook-Pro minimax % python3 -m timeit 'x=[1,2,3,4,5,6]'10000000 loops, best of 5: 26.9 nsec per loop(base) guohu@guohudeMacBook-Pro minimax % python3 -m timeit 'x=(1,2,3,4,5,6)' 50000000 loops, best of 5: 5.17 nsec per loop
1.如果存储的数据和数量不变,例如一个函数返回经纬度,那么选元组更适合