[Tutor] Tuple - Immutable ?

Walter Prins wprins at gmail.com
Thu Mar 8 12:23:37 CET 2012


On 8 March 2012 11:11, Sudip Bhattacharya <sudipb at sudipb.com> wrote:
>>>> s=(1,2,3)
>>>> s=s+(4,5,6)
>>>>s
> (1,2,3,4,5,6)
>
> The tuple has changed.

No, the tuple hasn't changed.  That's a *new* tuple.  Consider:

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s=(1,2,3)
>>> id(s)
44137280L
>>> s=s+(4,5,6)
>>> id(s)
34277416L
>>> l=[1,2,3]
>>> id(l)
44152072L
>>> l.extend([4,5,6])
>>> id(l)
44152072L
>>> l
[1, 2, 3, 4, 5, 6]
>>> l=l+[7,8,9]
>>> id(l)
44150856L
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

So, as you can see, in the case of the tuple, the addition actually
creates a *new* tuple (different id) that consists of the members of
the 2 input tuples, whereas in the case of the list, since the list is
mutable, the same list (same id) is *changed* when you add another
list to it.

Walter


More information about the Tutor mailing list