Lists and Tuples and Much More

7stud bbxx789_05ss at yahoo.com
Fri Apr 13 02:02:26 CEST 2007


> Yes. Tuples are immutable - once created, they can't change.

Just to explain that statement a little better.  If you do this:


t = (1, 2, ["red", "white"])
t[2].append("purple")
print t    #(1, 2, ['red', 'white', 'purple'])


It sure looks like t changed, and therefore t is NOT immutable--and
the whole "tuples are immutable" mantra is a lie.  However, the list
itself isn't actually stored inside t.  What's stored inside t is
python's internal id for the list.  So suppose python gave the list
the internal id: 10008.  The tuple really looks like this:

t = (1, 2, <10008>)

And no matter what you do to the list: append() to it, sort() it,
etc., the list's id remains the same.  In that sense, the tuple is
immutable because the id stored in the tuple never changes.

In actuality, the numbers 1 and 2 aren't stored in the list either--
python has internal id's for them too, so the tuple actually looks
like this:

t = (<56687>, <93413>, <10008>)
       |         |        |
       |         |        |
       |         |        |
       V         V        V
       1         2        ["red", "white", "purple"]


Because of that structure, you can create situations like this:

>>> lst = ["red", "white"]
>>> t1 = (1, 2, lst)
>>> t2 = (15, 16, lst)
>>> print t1
(1, 2, ['red', 'white'])
>>> print t2
(15, 16, ['red', 'white'])
>>> lst.append("purple")
>>> print lst
['red', 'white', 'purple']
>>> print t1
(1, 2, ['red', 'white', 'purple'])
>>> print t2
(15, 16, ['red', 'white', 'purple'])
>>>

lst, t1, and t2 all refer to the same list, so when you change the
list, they all "see" that change.  In other words, the names lst,
t1[2], and t2[2] all were assigned the same python id for the original
list ["red", "white"].  Since all those names refer to the same list,
any of those names can be used to change the list.








More information about the Python-list mailing list