Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #8248

Re: what happens inside?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: what happens inside?
Date 2011-06-22 19:00 -0400
References <BANLkTim5-pusEdT2Qhm-0NJtbazLJMvxXA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.304.1308783688.1164.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: what happens inside? Terry Reedy <tjreedy@udel.edu> - 2011-06-22 19:00 -0400

csiph-web