Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you assign new value to tuples with concatenation?

Tags:

python

tuples

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?

like image 634
Oliver H Avatar asked Dec 17 '22 20:12

Oliver H


2 Answers

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
like image 170
deceze Avatar answered Feb 15 '23 22:02

deceze


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.

like image 24
elpidaguy Avatar answered Feb 15 '23 22:02

elpidaguy