I was playing with python to try to reduce memory usage using various methods. One question that arose is if there’s a way to pass a list slice as reference to the original list.
The reason was the following simple code:
def reverse_string_inplace(self, s: list[str]) -> None:
if len(s) <= 1:
return
s[0], s[-1] = s[-1], s[0]
self.reverseString(s[1:-1])
As you can guess, the intended output for, let’s say, string = ['1','2','3','4','5']
would be string = ['5','4','3','2','1']
. However, the output gets to be string = ['5','2','3','4','1']
. That happens because the the slice s[1:-1]
is copied to the new recursive call, which switches the ‘2’ and the ‘4’ of the copy, not of the original.
Would there be any way in python (without passing indexes as parameters) to pass s[1:-1]
as a reference to a portion of the list instead of passing the copy of it?
why can’t you just pass s? it would pass the whole list in order. Its less code and s[1:-1]
is the same as s
.
SmoothTurtle872 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.