1

If tuples are supposed to be immutable (which are in most cases), why can we change their data in the following way :

tuple = (1, 2, 3)

tuple += (4, 5)

print (tuple) #outputs (1, 2, 3, 4, 5)
wotmane
  • 11
  • 1

3 Answers3

4

You didn't mutate a tuple, you made a new one.

>>> tup = (1, 2, 3)
>>> tup2 = tup
>>> tup
(1, 2, 3)
>>> tup2
(1, 2, 3)
>>> tup += (4, 5)
>>> tup
(1, 2, 3, 4, 5)
>>> tup2
(1, 2, 3)

Initially, tup and tup2 refer to the same tuple. After the tup += (4, 5), tup refers to a new tuple and tup2 still refers to the old one. No mutation occurred.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples.

Rima
  • 1,447
  • 1
  • 6
  • 12
1

In your example, += sneakily stops being an in-place operator. tuple is a different tuple from when you started, because adding two tuples necessarily produces a new one, because tuples are immutable.

kindall
  • 178,883
  • 35
  • 278
  • 309