Mutable objects inside tuples - good or bad?

Devin Jeanpierre jeanpierreda at gmail.com
Sun Apr 6 03:55:58 EDT 2014


On Sun, Apr 6, 2014 at 12:25 AM, Gary Herron
<gary.herron at islandtraining.com> wrote:
> On 04/05/2014 11:53 PM, John Ladasky wrote:
>>
>> I find this programming pattern to be useful... but can it cause problems?
>
> No.
>
> What kind of problems are you considering?  It won't break Python. It's
> perfectly legal code.

Agreed. Putting mutable objects inside tuples is common and totally OK.

> The tuple c is still immutable, consisting of two specific objects, and (as
> always) without regard to the specifics or contents of those two objects.

You can choose to define mutability that way, but in many contexts
you'll find that definition not very useful.

c is such that you could have another variable d, where the following
interpreter session fragment is easily possible:

>>> c == d
True
>>> foo(c)
>>> c == d
False

-- Devin

>> Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
>> [GCC 4.8.1] on linux
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>
>>>>> a = [1,2,3]
>>>>> b = [4,5,6]
>>>>> c = (a,b)
>>>>> c
>>
>> ([1, 2, 3], [4, 5, 6])
>>>>>
>>>>> c[0][0] = 0
>>>>> c
>>
>> ([0, 2, 3], [4, 5, 6])
>>
>> Comments appreciated.
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list