list = [1,2,3]
list[0]=10
print(list)
# [10, 2, 3]
tuple = ([2,4,6],2,"ni")
tuple[0].append(1)
print(tuple)
# ([2, 4, 6, 1], 2, 'ni')
tuple[0]=["1",3,5]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-a4d7b2650c1a> in <module>()
7 print(tuple)
8
----> 9 tuple[0]=["1",3,5]
TypeError: 'tuple' object does not support item assignment
** 储存方式和性能差别
列表除了存储的数据之外,还需要额外的信息,比如指针,长度大小,因此占用空间大一些。
列表长度可变,每次增加或删减操作时,分配空间时都会额外多分配一些
所以,元组的性能更优,更轻量,尤其体现在初始化上,在根据索引查找时,性能相差不大。
python -m timeit 'x = (1,2,3,4,5,6)'# 10000000 loops, best of 3: 0.0722 usec per loop
python -m timeit 'x = [1,2,3,4,5,6]'# 1000000 loops, best of 3: 0.238 usec per loop