If x is list, why does x += “ha” work, while x = x + “ha” throws an exception?

前端 未结 3 908
暖寄归人
暖寄归人 2021-01-31 14:35

From what little I know, + op for lists only requires the 2nd operand to be iterable, which \"ha\" clearly is.

In code:

>>> x = []
>>>          


        
3条回答
  •  无人及你
    2021-01-31 15:19

    You're thinking about it backwards. You're asking why x = x + 'ha' throws an exception, given that x += 'ha' works. Really, the question is why x += 'ha' works at all.

    Everyone agrees (I hope) that 'abc' + 'ha' and [1, 2, 3] + ['h', 'a'] should work. And in these cases, overloading += to do in-place modification seems reasonable.

    The language designers decided that [1, 2, 3] + 'ha' shouldn't, because you're mixing different types. And that seems reasonable as well.

    So the question is why they decided to allow mixing different types in the case of x += 'ha'. In this case, I imagine there are a couple reasons:

    • It's a convenient shorthand
    • It's obvious what happens (you append each of the items in the iterable to x)

    In general, Python tries to let you do what you want, but where there's ambiguity, it tends to force you to be explicit.

提交回复
热议问题