Yes, you are right, it is O(n) where n - length of list. Look here for more information: https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
Answer from Serenity on Stack OverflowYes, you are right, it is O(n) where n - length of list. Look here for more information: https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
If you look into the implementation of the reverse method here, then it looks as follows:
static PyObject *
listreverse(PyListObject *self)
{
if (Py_SIZE(self) > 1)
reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Py_RETURN_NONE;
}
So, the operation is actually delegated to reverse_slice. Then, let's look into it:
static void
reverse_slice(PyObject **lo, PyObject **hi)
{
assert(lo && hi);
--hi;
while (lo < hi) {
PyObject *t = *lo;
*lo = *hi;
*hi = t;
++lo;
--hi;
}
}
So, here are 2 indices initially set at the start and end of the list. Then, at each iteration of while loop, elements at respective indices are swapped:
PyObject *t = *lo;
*lo = *hi;
*hi = t;
And then the left index gets incremented and the right one decremented:
++lo;
--hi;
The loop goes on as long as the right index exceeds the left one. So, if there're n elements in the list, then there will be performed n/2 iterations and hence the time complexity is O(n)
a[::-1] traverse array a of size n in backward order. What'd be the time complexity of this?
When should I use NumPy to reverse a list instead of native Python methods?
What is the time complexity of the two-pointer approach?
Are there any trade-offs between using built-in functions and manual methods to reverse a list?
I'm still thinking in the mentality of how this could be done in C, and it seems like Python should have a way to play with the indexes in reverse order under the hood to make this operation O(1), so why is reversing a list O(n)? Or at least in CPython
I'm aware that iterating through said reversed list is at least O(n) anyway.