Sobes.tech
Intern — Middle

Reversing a list without using built-in methods

livecode

Task condition

It is necessary to write a function that reverses the order of elements in a list without using the .reverse() method and without slicing like [::-1]. The list should be modified "in place", not a new object created.

def manual_reverse(seq: list) -> list:
    left, right = 0, len(seq) - 1
    while left < right:
        seq[left], seq[right] = seq[right], seq[left]
        left += 1
        right -= 1
    return seq

manual_reverse([1, 2, 3])

arr = [1, 2, 3]
res = manual_reverse(arr)
print(id(arr), id(res))
print([1, 2] is [1, 2])