Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens internally when concatenating two lists in Python?

When concatenating two lists,

a = [0......, 10000000]
b = [0......, 10000000]

a = a + b

does the Python runtime allocate a bigger array and loop through both arrays and put the elements of a and b into the bigger array?

Or does it loop through the elements of b and append them to a and resize as necessary?

I am interested in the CPython implementation.

like image 938
user10714010 Avatar asked Oct 20 '25 14:10

user10714010


1 Answers

In CPython, two lists are concatenated in function list_concat.

You can see in the linked source code that that function allocates the space needed to fit both lists.

size = Py_SIZE(a) + Py_SIZE(b);
np = (PyListObject *) list_new_prealloc(size);

Then it copies the items from both lists to the new list.

for (i = 0; i < Py_SIZE(a); i++) {
    ...
}
...
for (i = 0; i < Py_SIZE(b); i++) {
    ...
}
like image 167
zvone Avatar answered Oct 22 '25 02:10

zvone