Python 中的可变/不可变对象
Python 中哪些对象是可变的(mutable),哪些是不可变的(immutable)?区别及注意事项?
回答
我是大山
不可变对象(修改会创建新对象):
- int, float, complex
- str
- tuple
- bytes
- frozenset
可变对象(可直接修改):
- list
- dict
- set
- bytearray
- 自定义类实例(通常可变)
# 不可变
s = 'hello'
s[0] = 'H' # TypeError: 'str' object does not support item assignment
# 可变
lst = [1, 2, 3]
lst[0] = 99 # 可以
注意:元组中若包含可变对象,该可变对象的内容可以改变:t = ([1], 2); t[0][0] = 99。