[Python] a mutable type inside an immutable container

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm a bit confused about modifying tuple members. The following doesn't work:

    >>> thing = (['a'],)
    >>> thing[0] = ['b']
    TypeError: 'tuple' object does not support item assignment
    >>> thing
    (['a'],)


    But this does work:

    >>> thing[0][0] = 'b'
    >>> thing
    (['b'],)


    Also works:

    >>> thing[0].append('c')
    >>> thing
    (['b', 'c'],)


    Doesn't work, and works (huh?!):

    >>> thing[0] += 'd'
    TypeError: 'tuple' object does not support item assignment
    >>> thing
    (['b', 'c', 'd'],)


    Seemingly equivalent to previous, but works:

    >>> e = thing[0]
    >>> e += 'e'
    >>> thing
    (['b', 'c', 'd', 'e'],)


    So what exactly are the rules of the game, when you can and can't modify something inside a tuple? It seems to be more like prohibition of using the assignment operator for tuple members, but the last two cases are confusing me.

    Continue reading...

Compartilhe esta Página