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


Groups > comp.lang.python > #8221

Re: what happens inside?

References <BANLkTim5-pusEdT2Qhm-0NJtbazLJMvxXA@mail.gmail.com>
From Noah Hall <enalicho@gmail.com>
Date 2011-06-22 16:58 +0100
Subject Re: what happens inside?
Newsgroups comp.lang.python
Message-ID <mailman.286.1308758352.1164.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Jun 22, 2011 at 4:45 PM, Chetan Harjani
<chetan.harjani@gmail.com> wrote:
> why tuples are immutable whereas list are mutable?
Because an immutable data type was needed, and a mutable type was also needed ;)

> 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.

That's because y points to an object. When you assign x = y, you say
"assign name x to object that's also pointed to by name y". When you
change the list using list methods, you're changing the actual object.
Since x and y both point to the same object, they both change.
However, if you then assign y = [1], name y no longer points to the
original object. x still remains pointing to the original object.

>>> a = [1,2] # assign name a to object [1,2]
>>> b = a # assign name b to object referred to by name a
>>> b
[1, 2]
>>> a = [3,4] # assign name a to object [3,4]
>>> b
[1, 2]
>>> a
[3, 4]

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


Thread

Re: what happens inside? Noah Hall <enalicho@gmail.com> - 2011-06-22 16:58 +0100

csiph-web