发布于 5年前

Python 列表和元组之间有什么区别?

它们的最大区别在于 list 是可变(mutable)的,而 tuple 是不可变(immutable)的。举个例子:

In [1]: a_list = [1]

In [2]: a_list[0] = 2

In [3]: a_list.append(3)

In [4]: a_tuple = (1,)

In [5]: a_tuple.append(2)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-0cdd0de979c0> in <module>
----> 1 a_tuple.append(2)

AttributeError: 'tuple' object has no attribute 'append'

In [6]: a_tuple[0] = 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-d3d07cfb4a8a> in <module>
----> 1 a_tuple[0] = 2

TypeError: 'tuple' object does not support item assignment

可以看到,list 的长度,以及它本身的值都是可变的,而 tuple 的长度和 tuple 本身的值都是不可变的。

©2020 edoou.com   京ICP备16001874号-3