Python list += iterable 的行为是否记录在任何地方?

2022-01-24 00:00:00 python operators containers

问题描述

在 Python 中,list += x 似乎适用于任何可迭代的 x:

在[6]中:l = []在 [7] 中:l += [1]在 [8] 中:l += (2, 3)在 [9] 中: l += xrange(5)在[10]中:l输出[10]:[1、2、3、0、1、2、3、4]

这种行为是否记录在任何地方?

为了与 list + x 进行对比,后者仅在 x 也是 list 时才有效.这在 文档.

解决方案

来自 Guido van Rossum:p><块引用>

它的工作方式与 .extend() 相同,只是它也返回 self.一世找不到解释这一点的文档.:-(

这里是取自 listobject.c:

list_inplace_concat(PyListObject *self, PyObject *other){PyObject *结果;结果 = 列表扩展(自我,其他);如果(结果 == NULL)返回结果;Py_DECREF(结果);Py_INCREF(自我);返回(PyObject *)自我;}

我已提交错误报告以修复文档:http://bugs.python.org/issue16701

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]: l += xrange(5)

In [10]: l
Out[10]: [1, 2, 3, 0, 1, 2, 3, 4]

Is this behaviour documented anywhere?

To contrast this with list + x, the latter only works if x is also a list. This is spelled out in the documentation.

解决方案

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

相关文章