I am new to Python. I was recently confused by a syntax "[list] * k". I want to understand how Python actually executes it. Example:
>>> l = [1, 2] * 10
>>> l
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
Assume len(list) = n, when Python interprets it, I have following guesses with my limited knowledge.
it uses list.extend(list) method. Thus it will take up O(n * k) space and use O(n * k) time.
it only copies the reference of the original list and make k copy of it. Thus it will take up O(k) space and use O(k) time.
If my 2nd guess is the case, why and how following statement works?
>>> l[3] = 100
>>> l
[1, 2, 1, 100, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
Any official design doc, source code and PEP reference is strongly welcomed!
Follow up,
The source code link provided by @JoshLee and @MSeifert is very helpful in understanding the internal mechanism. See here at list_repeat
The following code snippet confirms the space complexity is O(n * k).
size = Py_SIZE(a) * n;
Also following code snippet confirms the time complexity is O(n * k).
p = np->ob_item;
items = a->ob_item;
for (i = 0; i < n; i++) {
for (j = 0; j < Py_SIZE(a); j++) {
*p = items[j];
Py_INCREF(*p);
p++;
}
}