Why must Python list addition be homogenous?

前端 未结 4 1120
生来不讨喜
生来不讨喜 2020-12-30 23:31

Can anyone familiar with Python\'s internals (CPython, or other implementations) explain why list addition is required to be homogenous:

In [1]: x = [1]

In          


        
4条回答
  •  佛祖请我去吃肉
    2020-12-31 00:00

    I believe Python designers made addition this way so that '+' operator stays consistently commutative with regard to result type: type(a + b) == type(b + a)

    Everybody expects that 1 + 2 has the same result as 2 + 1. Would you expect [1] + 'foo' to be the same as 'foo' + [1]? If yes, what should be the result?

    You have 3 choices, you either pick left operand as result type, right operand as result type, or raise an error.

    += is not commutative because it contains assignment. In this case you either pick left operand as result type or throw. The surprise here is that a += b is not the same as a = a + b. a += b does not translate in English to "Add a to b and assign result to a". It translates to "Add a to b in place". That's why it doesn't work on immutables such as string or tuple.

    Thanks for the comments. Edited the post.

提交回复
热议问题