[Python] Concatenating list and tuple with += operator [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    The question is not about how to concatenate list and tuple but about behaviour of the operator +=.

    Let's assume we have a tuple

    t = (3, )


    If we siply execute following expression it fails with TypeError: can only concatenate list (not "tuple") to list

    [1, 2] + t


    Obviously this can be fixed with explicit type cast

    [1, 2] + list(t)


    Similarly, if we try below we get TypeError

    x2 = [1, 2]
    x2 = x2 + t
    x2


    The question is why following works fine?

    x1 = [1, 2]
    x1 += t
    x1


    I presume it does implicit conversion but appreciate more substantial eplanation and links to official documentation.

    Thanks

    Continue reading...

Compartilhe esta Página