First, don't do this. Mutating data structures makes your coworkers hate you. But if you must, consider:
def mutate(lst):
backward = lst[::-1]
lst.clear()
lst.extend(backward)
a = [1,2,3,4]
print(a)
print(id(a))
mutate(a)
print(a)
print(id(a))
The mutate function makes a reversed copy of its inputs. Then it clears the contents of the list that was passed in so that it's empty. Finally, it fills that empty list with the reversed copy. This way the original object is mutated in place and retains its original ID.
Alternatively, if you're extremely resource limited and are willing for the code to be slower in exchange for not having to temporarily duplicate the input list, you could swap the first and last items, then the second and second-to-lsat items, and so on until you reach the middle of the list:
def mutate_by_swapping(lst):
last_index = len(lst) - 1
for i in range(len(lst) // 2):
lst[i], lst[last_index - i] = lst[last_index - i], lst[i]
reversedfunction orreturnstatement?forloop inside thereverse(x)function. So, you need to indent theforloop appropriately.