We know that tuple is immutable in Python. Then why the below code works?
3 * ('a','b','c')
Gives output as below:
('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
You created a new tuple, see how id
s differ:
>>> a = (1,2,3)
>>> id(a)
4505615456
>>> b = a * 3
>>> id(b)
4504578232
However, what you've accomplished will create also a new list if you did the equivalent:
>>> a = [ 1, 2, 3 ]
>>> id(a)
4505618120
>>> b = a * 3
>>> id(b)
4505618248
You can see the list is mutable with the following code:
>>> a = [ 1, 2, 3]
>>> id(a)
4505618568
>>> a.append(1)
>>> a.append(2)
>>> a.append(3)
>>> a
[1, 2, 3, 1, 2, 3]
>>> id(a)
4505618568
You can't achieve the same with a tuple.
One last thing to convince yourself that tuples are immutable:
>>> a = (1, 2, 3)
>>> a[0]
1
>>> a[0] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(1, 2, 3)
versus the equivalent with a list:
>>> a = [1, 2, 3]
>>> a[0]
1
>>> a[0] = 10
>>> a
[10, 2, 3]
For more info and pitfalls, see this interesting article http://radar.oreilly.com/2014/10/python-tuples-immutable-but-potentially-changing.html
"Immutable" means "Can't be modified," not "Can't be used to construct other data." The latter wouldn't make much sense in a container, anyway! What use is there of a tuple other than containing data for later use?
Your sample code 3 * ('a', 'b', 'c') = ('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
just shows that multiplying a tuple by a scalar creates a new tuple with duplicating elements. The following is NOT possible however:
tup = ('a', 'b', 'c')
tup[0] = 'z' # fails, because tuples are not mutable
`('a','b','c')` is a tuple.
And 3 * ('a','b','c')=('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
is another tuple which is made of 3 times of ('a','b','c')
. If you think x =('a','b','c')
then 3*('a','b','c')
= x+x+x` (look, x and x+x+x is not same!).Both of them are separate tuples. In this similar rule 1 and 1+1+1 are not same!
You will find a proof in Benjamin Toueg's answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.