在Python中,元组是不可变的吗?

4 投票
5 回答
1575 浏览
提问于 2025-04-18 09:52

它说:

一旦创建了元组,就不能以任何方式改变它。

但是当我这样做的时候:

t1=(4,5,8,2,3)
t1=t1+(7,1)
print(t1)

这个元组变成了 (4, 5, 8, 2, 3, 7, 1);这是为什么呢?“元组是不可变的”到底是什么意思?

5 个回答

0

我不能说是的。

Python中的元组有一个让人意想不到的特点:它们是不可变的,但它们的值可能会改变。这种情况发生在元组中包含了对任何可变对象的引用,比如字典或列表。

>>> t1 = ('Bangalore', ['HSR', 'Koramangala'])
>>> print(t1)
('Bangalore', ['HSR', 'Koramangala'])
>>> print(id(t1)) # ID of tuple
4619850952

>>> place = t1[1]
>>> place.append('Silk Board')  # Adding new value to the list
>>> print(t1) 
('Bangalore', ['HSR', 'Koramangala', 'Silk Board'])
# Surprisingly tuple changed, let's check the ID
>>> print(id(t1)) # No change in the ID of tuple
4619850952

>>> print(t1[0])
Bangalore
>>> print(id(t1[0])) # ID of tuple's first element
4641176176
>>> print(id(t1[1])) # ID of tuple's second element (List)
4639158024
# These are the ref. id's of the tuple

>>> place.append('Agara')
>>> print(t1) 
('Bangalore', ['HSR', 'Koramangala', 'Silk Board', 'Agara'])
>>> print(id(t1))
4619850952
# Still no change, are they Immutable ??

>>> print(id(t1[1])) # The tuple having a ref. of Mutable object
4639158024

在上面的例子中,元组和列表的ID没有改变。这是因为元组中存储的是对对象的引用,而不是对象本身的值。

2

是的,它们是不可变的。

t1 = t1 + (7,1)

创建一个新的元组...并不是在修改旧的那个。

试试这个:

t1[0] = 5
2

简单来说,当你写 t1=t1+(7,1) 的时候,其实是在把 t1 重新指向一个新的内存位置。Python 说的不可变,意思是你不能通过切片的方式来改变它们:

>>> t1=(4,5,8,2,3)
>>> t1[0] = 9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> 

因为这样会创建一个新的元组:

>>> t1=(4,5,8,2,3)
>>> id(t1)
4467745808
>>> t1 = t1+(9,)
>>> id(t1)
4468302112
>>> 

你可以看到,列表是会 保持 id 的:

>>> lst = [4, 5, 8, 2, 3]
>>> id(lst)
4468230480
>>> lst[0] = 6
>>> id(lst)
4468230480
>>> 

这就是 Python 对于 不可变性 的定义。

3

你的代码中没有任何元组发生变化。名字 t1 只是指向了一个新的、不同的元组。原来的元组对象并没有改变,你只是不再使用它了。

10

是的,元组是不可变的;一旦创建,就不能更改。t1=t1+(7,1) 这行代码会创建一个 新的元组,并把它赋值给名字 t1。这 并不会 改变原来那个名字所指向的元组对象。

示例:

>>> t = (1, 2, 3)
>>> id(t)
4365928632
>>> t = t + (4, 5)
>>> id(t)
4354884624 # different id, different object

撰写回答