Skip to content

[C API] PyList_Extend() must not shrink the list #162894

Not planned

Description

@vstinner

Bug report

The PyList_New(n) function has a parameter to preallocate items to build a list in an efficient way. An usual way to use is to call PyList_New(n) to preallocate n items and then call Py_SET_SIZE(list, 0) to set the size to 0. When doing that, PyList_Extend() can shrink the list if the new_size is smaller than the half of the allocated size, which is not expected behavior. I would expect the list to keep its allocated items while we are growing the list!

I discovered the issue with the implementation of the PyListBuilder API: see PR gh-160127. Internally, PyListBuilder_Create(n) calls PyList_New(n) and then Py_SET_SIZE(list, 0) (well, the exact implementation is different, but we get a similar behavior).

I didn't find code in the Python stdlib which calls PyList_New(n) followed by Py_SET_SIZE(list, 0). The usual pattern is either to PyList_New(n) and set items (and then sometimes shrink the list using Py_SET_SIZE()), or call PyList_New(0) and then call Append/Extend on it.

I propose to change the behavior to only shrink the list on operations which actually shrink the list such as list.pop() or del list[start:end].

Example showing the issue:

import _testcapi, _testlimitedcapi

def size(lst):
    return f'{len(lst)}/{_testcapi._list_get_allocated(lst)}'

def join_two_lists(list1: list, list2: list):
    result = _testlimitedcapi.list_new(len(list1) + len(list2))
    _testcapi._list_set_size(result, 0)
    print("after PyList_New, len/allocated=", size(result))
    result.extend(list1)
    print("after the first PyList_Extend, len/allocated=", size(result))
    result.extend(list2)
    print("after the second , len/allocated=", size(result))
    return result

list1 = list(range(3))
list2 = list(range(3, 1_000))
join_two_lists(list1, list2)

Current output:

after PyList_New, len/allocated= 0/1000
after the first PyList_Extend, len/allocated= 3/8
after the second , len/allocated= 1000/1000
  • The first PyList_Extend() call shrinks the list from 1000 items to only 8 items (delete 992 items).
  • The second PyList_Extend() call enlarges the list from 8 items to 1000 items (add 992 items)... undo what the first PyList_Extend() call did :-(

The example requires PR gh-160127 (to get _testcapi._list_get_allocated()) + this additional patch (to get _testcapi._list_set_size()):

Details
diff --git a/Modules/_testcapi/list.c b/Modules/_testcapi/list.c
index d39107ec5a8..fb0959588d5 100644
--- a/Modules/_testcapi/list.c
+++ b/Modules/_testcapi/list.c
@@ -65,6 +65,19 @@ list_extend(PyObject* Py_UNUSED(module), PyObject *args)
 }
 
 
+static PyObject *
+list_set_size(PyObject* Py_UNUSED(module), PyObject *args)
+{
+    PyObject *list;
+    Py_ssize_t size;
+    if (!PyArg_ParseTuple(args, "On", &list, &size)) {
+        return NULL;
+    }
+    Py_SET_SIZE(list, size);
+    Py_RETURN_NONE;
+}
+
+
 static PyObject*
 test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored))
 {
@@ -365,6 +378,7 @@ static PyMethodDef test_methods[] = {
     {"list_clear", list_clear, METH_O},
     {"list_extend", list_extend, METH_VARARGS},
     {"test_list_api", test_list_api, METH_NOARGS},
+    {"_list_set_size", list_set_size, METH_VARARGS},
     {"_list_get_allocated", _list_get_allocated, METH_O},
     {NULL},
 };

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    performance
    on Nov 30, 2026
  2. vstinner commented on Nov 30, 2026

    @vstinner
    MemberAuthor
  3. encukou commented on Dec 1, 2026

    @encukou
    Member

    Hmm, this is a bigger change than needed for PyListBuilder; it affects long-standing API. How sure can we be that people don't do this on purpose -- perhaps something like PyList_New+PyList_SET_ITEM*+Py_SET_SIZE+PyList_Extend(empty_tuple) to preallocate a big list, fill it and then shrink to size? (It's a hack, but we didn't really offer a good way to do this AFAIK.)

    I'd much prefer doing this in an internal helper for PyListBuilder, and perhaps then a more easily revertable PR for PyList_Extend.
    (Sadly this probably needs a new list_resize_grow, and an extra shrink call at the end of public extend APIs.)

  4. added
    interpreter-core
    on Dec 1, 2026
  5. vstinner commented on Dec 1, 2026

    @vstinner
    MemberAuthor

    Oh. I wrote a long comment to explain that nobody relies on the current behavior of PyList_Append/Extend() (shrink the list). But then I searched for shrink.*list regex in Cython and I found:

        def _handle_simple_method_list_extend(self, node, function, args, is_unbound_method):
            """Replace list.extend([...]) for short sequence literals values by sequential appends
            to avoid creating an intermediate sequence argument.
            """
            ...
            # Use ListComp_Append() for all but the last item and finish with PyList_Append()
            # to shrink the list storage size at the very end if necessary.
            ...
            new_node = ExprNodes.PythonCapiCallNode(
                node.pos, "__Pyx_PyList_Append", self.PyObject_Append_func_type,
                args=[cloned_obj, arg],
                is_temp=True,
                utility_code=load_c_utility("ListAppend"))
            for arg in items[-2::-1]:
                ...
                new_node = ExprNodes.binop_node(
                    node.pos, '|',
                    ExprNodes.PythonCapiCallNode(
                        node.pos, "__Pyx_ListComp_Append", self.PyObject_Append_func_type,
                        args=[cloned_obj, arg], py_name="extend",
                        is_temp=True,
                        utility_code=load_c_utility("ListCompAppend")),
                    new_node,
                    type=PyrexTypes.c_returncode_type,
                )
            ...

    So there is at least one Cython function which relies on the fact that PyList_Append() shrinks a list.

  6. vstinner commented on Dec 1, 2026

    @vstinner
    MemberAuthor

    I abandon this approach since I found at least one project (Cython) relying on the fact that PyList_Append() shrinks the list.

    Instead, I wrote #162969 to only prevent shrinking the list in PyListBuilder methods (leave existing PyList functions unchanged).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coreperformancetopic-C-APItype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions