Python
Mutable Sequences
Implement a function reverse that takes a list as an argument and reverses the list. You should mutate the original list, without creating any new lists. Do NOT return anything. Do not use any built-in list functions such as reverse().
def reverse(lst):
"""Reverses lst in place (i.e. doesn't create new lists).
>>> L = [1, 2, 3, 4]
>>> reverse(L)
>>> L
[4, 3, 2, 1]
"""
def reverse(lst): """Reverses lst in place (i.e. doesn't create new lists). >>> L = [1, 2, 3, 4] >>> reverse(L) >>> L [4, 3, 2, 1] """ for i in range(len(lst) // 2): lst[i], lst[len(lst) - i - 1] = lst[len(lst) - i - 1], lst[i] # Testing the function here. ignore/remove the code below if not required L = [1, 2, 3, 4] print(L) reverse(L) print(L) L = [1, 2, 3, 4, 5] print(L) reverse(L) print(L)
Get Answers For Free
Most questions answered within 1 hours.