I was trying to write a program that would reverse a list in python3. I first tried:
def reverse(lst):
""" Reverses lst in place.
>>> x = [3, 2, 4, 5, 1]
>>> reverse(x)
>>> x
[1, 5, 4, 2, 3]
"""
n = len(lst)
for i in range(n//2):
lst[i], lst[n-i-1] = lst[n-i-1], lst[i]
It failed and the x I got was the original value. However, when I changed my code to this, it worked:
def reverse(lst):
""" Reverses lst in place.
>>> x = [3, 2, 4, 5, 1]
>>> reverse(x)
>>> x
[1, 5, 4, 2, 3]
"""
n = len(lst)
for i in range(n//2):
temp = lst[i]
lst[i] = lst[n-i-1]
lst[n-i-1] = temp