what happens inside?

Noah Hall enalicho at gmail.com
Wed Jun 22 11:58:50 EDT 2011


On Wed, Jun 22, 2011 at 4:45 PM, Chetan Harjani
<chetan.harjani at 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]



More information about the Python-list mailing list