简体   繁体   English

python元组赋值(如果元组可变)

[英]python tuple assignment if a tuple is mutable

I am new to python. 我是python的新手。 Tuples are said to be immutable but why is that we can do something like this. 据说元组是不变的,但是为什么我们可以做这样的事情。 ie to concatenate and change the original value 即连接并更改原始值

a=(1,2,3)
>>> a
(1, 2, 3)
>>> b=(4,5,6)
>>> b
(4, 5, 6)
>>> a=a+b
>>> a
(1, 2, 3, 4, 5, 6)

in this case aren't we changing the values in the tuple a? 在这种情况下,我们不是要更改元组a中的值吗?

No, you're making a new tuple. 不,您要创建一个新的元组。 Consider. 考虑。

>>> a = (1, 2, 3)
>>> a1 = a

Now a1 and a are the same tuple. 现在a1a是相同的元组。 Not just similar looking ones; 不仅看起来相似; they're the same . 他们是一样的 Then 然后

>>> b = (4, 5, 6)
>>> a = a + b

Now a is (1, 2, 3, 4, 5, 6) . 现在a(1, 2, 3, 4, 5, 6) Did we change the first tuple we made? 我们是否更改了我们制作的第一个元组? Let's ask Python. 让我们问一下Python。

>>> a
(1, 2, 3, 4, 5, 6)
>>> a1
(1, 2, 3)

Nope, the original tuple stayed the same. 不,原始元组保持不变。

This distinction is important. 这种区别很重要。 You made a new tuple and happened to give it the same name. 您创建了一个新的元组,并偶然给它取了相同的名称。 That means that, if you were writing a complicated program with a huge object hierarchy, the change you just made to a wouldn't break any of the other objects or code that depended on the previous value of a . 这意味着,如果你有一个巨大的对象层次写一个复杂的程序,你只需所做的更改a不会打破任何依赖于以前的值的其他对象或代码的a It only broke your particular a variable that you control. 它不仅打破您的特定a你控制的变量。 On the other hand, if we had a list a = [1, 2, 3] and started appending to it, then any other object who happened to hold a reference to that list is now going to see the changes, which results in messy errors at a distance. 另一方面,如果我们有一个列表a = [1, 2, 3]并开始追加到列表中,那么碰巧持有对该列表的引用的任何其他对象现在都将看到更改,从而导致混乱远处的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM