[Solved] runtime of using [::-1] on a list [closed]


list.reverse operates in place. That means that it almost certainly does something like this under the hood:

for i in range(len(self) // 2):
     j = len(self) - 1 - i
     self[i], self[j] = self[j], self[i]

The actual method is implemented in C, so of course it will be much more verbose, especially in the swapping operation.

list[::-1] creates a copy of the original. The idea is similar, but since the reversal of not in place, you have the luxury of just writing to a destination index rather than swapping via a temporary object:

new = [None] * len(self)
for i in range(len(self)):
    j = len(self) - 1 - i
    new[j] = self[i]

The actual slice processing code is much more complex since it has to be able to accept integers and all sorts of unorthodox slice expressions that set custom start and stop bounds, and step sizes.

2

solved runtime of using [::-1] on a list [closed]