How Is A Tuple Immutable If You Can Add To It (a += (3,4))
Solution 1:
In the example, you're not changing the actual tuple, you're only changing the tuple that the variable a
is pointing to. In this example a += (3, 4)
is the same as a = a + (3, 4)
. If we check the id
of a
before and after the operation, we can see the difference:
>>>a = (1, 2)>>>id(a)
60516360
>>>a += (3, 4)>>>id(a)
61179528
With lists, +=
calls .extend()
on the list, which changes it in-place.
>>>b = [1, 2]>>>id(b)
62480328
>>>b += [3, 4]>>>id(b)
62480328
Notice that the id
of b
doesn't change after the operation.
Solution 2:
Tuple is of immutable type, means that you cannot change the values stored in the variable a
. For example, doing the following
>>>a = (1, 2)>>>a[0] = 3
throws up the error TypeError: 'tuple' object does not support item assignment
.
On the other hand, for a list,
>>>a = [1, 2]>>>a[0] = 3
this is perfectly valid because it is mutable.
What you are doing is reassigning values to the variable names.
a = a + (3, 4)
which just concatenates the two and reassigns it to the variable a
. You are not actually changing the value of the tuple.
For example, string
is immutable, and hence,
>>>name = "Foo">>>name[0] ='o'
throws up a similar error as above. But, the following is a reassignment and completely valid.
>>>name = name + " Bar">>>name
'Foo Bar'
and it just does a concatenation.
Post a Comment for "How Is A Tuple Immutable If You Can Add To It (a += (3,4))"