在 tuple/list 之间转换时会发生什么?

What happens when converting between tuple/list?

在将元组转换为列表或相反时,python 如何在内部进行转换。

它是"switch a flag"(现在你是不可变的,现在你不是!)还是遍历项目并转换它们?

元组和列表是完全不同的类型;因此,当将列表转换为元组或相反时,会创建一个 new 对象并复制元素引用。

Python 是否 通过深入到另一个对象的内部结构来优化它;例如,list(tupleobj) 本质上与 list().extend(tupleobj) 相同,其中 listextend function 然后使用 Python C API 函数简单地复制引用元组的 C 数组:

if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
    PyObject **src, **dest;
    b = PySequence_Fast(b, "argument must be iterable");
    if (!b)
        return NULL;
    n = PySequence_Fast_GET_SIZE(b);
    if (n == 0) {
        /* short circuit when b is empty */
        Py_DECREF(b);
        Py_RETURN_NONE;
    }
    m = Py_SIZE(self);
    if (list_resize(self, m + n) == -1) {
        Py_DECREF(b);
        return NULL;
    }
    /* note that we may still have self == b here for the
     * situation a.extend(a), but the following code works
     * in that case too.  Just make sure to resize self
     * before calling PySequence_Fast_ITEMS.
     */
    /* populate the end of self with b's items */
    src = PySequence_Fast_ITEMS(b);
    dest = self->ob_item + m;
    for (i = 0; i < n; i++) {
        PyObject *o = src[i];
        Py_INCREF(o);
        dest[i] = o;
    }
    Py_DECREF(b);
    Py_RETURN_NONE;
}

PySequence_Fast_ITEMS 是一个宏,用于访问元组的 C 结构中的 ob_item 数组,for 循环将该数组中的项目直接复制到 self->ob_item 数组(从偏移 m 开始)。