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

前端 未结 4 1651
鱼传尺愫
鱼传尺愫 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:31

    From Guido van Rossum:

    It works the same way as .extend() except that it also returns self. I can't find docs explaining this. :-(

    Here is the relevant source code taken from listobject.c:

    list_inplace_concat(PyListObject *self, PyObject *other)
    {
         PyObject *result;
    
         result = listextend(self, other);
         if (result == NULL)
             return result;
         Py_DECREF(result);
         Py_INCREF(self);
         return (PyObject *)self;
    }
    

    I've raised a bug report to have the documentation fixed: http://bugs.python.org/issue16701

提交回复
热议问题