Is the behaviour of Python's list += iterable documented anywhere?

前端 未结 4 1642
鱼传尺愫
鱼传尺愫 2020-11-29 09:21

It would appear that in Python, list += x works for any iterable x:

In [6]: l = []

In [7]: l += [1]

In [8]: l += (2, 3)

In [9]:          


        
4条回答
  •  孤独总比滥情好
    2020-11-29 09:33

    No (Guido confirms; thanks to Ashwini Chaudhary). The behaviour of += for sequences in general is underspecified. I conclude that it is not required by the specification that x + y where x is a list, and y some other iterable be an error (so other implementations could choose to allow it), and that other implementations could restrict += to require homogenous operands.

    However, the reasons not to do this are obvious: python in general tries to do the right thing with operands, rather than requiring rigid type equality. The real mystery is why heterogenous addition is not allowed with lists.

    Update: I've never really thought about the nonhomogenous addition problem, largely because itertools.chain is pretty much a complete solution to the problem.

    Comments from those more familiar with Python's internals are welcome to explain why addition is required to be homogenous. (Question here: Why must Python list addition be homogenous?)

提交回复
热议问题