what happens inside?

Terry Reedy tjreedy at udel.edu
Wed Jun 22 19:00:16 EDT 2011


On 6/22/2011 11:45 AM, Chetan Harjani wrote:
> why tuples are immutable whereas list are mutable?

Because tuples do not have mutation methods, which lists do.
Tuple and lists both have .__getitem__ but tuples do not have 
.__setitem__ or .__delitem__ (or .append, .extend, .sort, or .reverse).

> why when we do x=y where y is a list and then change a element in x, y
> changes too( but the same is not the case when we change the whole value
> in x ), whereas, in tuples when we change x, y is not affected and also
> we cant change each individual element in tuple. Someone please clarify.

For specific answers, you should give specific examples.

(1,2)[0] = 3 does not work because there is no tuple.__setitem__. But note:
 >>> a = ([1,2], 3)
 >>> b = a
 >>> a[0][0] = 4
 >>> b
([4, 2], 3)
Tuples containing mutables are not immutable all the way down.

They are also not hashable (if any element is not hashable) and cannot 
be used as dict keys.
 >>> hash(a)
Traceback (most recent call last):
   File "<pyshell#5>", line 1, in <module>
     hash(a)
TypeError: unhashable type: 'list'

-- 
Terry Jan Reedy




More information about the Python-list mailing list