Suppose I want to write a function that reverses the words in a sentence without using the split
function. Here is one possible solution:
def reverse_words_1(s):
i, n, r = 0, len(s), []
while i < n:
while i < n and s[i] == ' ': i += 1
if i == n: break
p = i
while i < n and s[i] != ' ': i += 1
# Instead of appending here and then reversing after the while
# loop is done, we could r.insert(0, ..). But insert is much
# slower than append/reverse because insert always requires that
# each pointer in the list must be copied and moved. Whereas
# append only requires copying if there isn't enough space for
# the new element in the currently allocated memory block.
# Helpful explanations:
# https://stackoverflow.com/questions/7776938/python-insert-vs-append
# https://bytes.com/topic/python/answers/34036-timing-difference-insert-vs-append-reverse
r.append( s[p : i] )
r.reverse()
return ' '.join(r)
The comment in my code notes that insert
is much slower than append/reverse
. But my comment really only compares the actions taken by insert
and append
. My comment doesn't address the actions or speed of reverse
.
So how does reverse
work in CPython? My guess is that reverse
is re-pointing the pointers in the list. Something like this:
def reverse(lst):
l, r = 0, len(lst) - 1
while l < r:
lst[l], lst[r] = lst[r], lst[l]
l += 1
r -= 1
Is this roughly how CPython internally performs the reverse
function?
If my guess about how reverse
works is correct, then I guess it's much faster to re-point pointers than it is to copy and move pointers?