Take the following code for example:
t=(1,2,3)
t+=(4,)
print(t)
The printed value is (1,2,3,4).Didn't the value of tuple t just got changed which is similar to an append/extend method for list objects?
You can concatenate tuples into a new tuple. You're replacing the value of t
entirely with a new value. You cannot modify an existing tuple. To illustrate:
t = (1, 2, 3)
u = t
t += (4,) # shorthand for t = t + (4,)
t == u # False
t is u # False
t
and u
do not refer to the same object anymore.
With mutable data structures, that would not be the case:
t = [1, 2, 3]
u = t
t.append(4)
t == u # True
t is u # True
Tuples are immutable. That is they can not be changed like lists in python. What you are doing is, just replacing old tuple with new tuple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With