+ 1
Tuple question
What's the output? TupleA = () TupleA =(1,2,3) TupleA+=(4,5,6) print(TupleA) If tuple can't change, why the answer is (123456) other than error in line2?
1 Resposta
+ 4
The actual tuple is not changed, but replaced by a new tuple, consisting of the values of the two old ones.
This whole mutability thing is basically about changing an object as it is, not re-assigning it.
For example you have a list arr:
arr.append(5)
This adds a 5 to the end of the list, so the object changes.
You can't do something like that with tuples.
With the = sign, you only give the name of the object to a new object.
a = (1, 2)
a = 'Whoops!'
The tuple a has not magically changed into a string - you just stripped the name off and pasted it to a newly created string instead.
(The tuple, now nameless, is silently and automatically deleted by Python.)