creating a reverse method for a python list from scratch
def reverse(data_list):
return data_list[::-1]
>> reverse([1,2,3,4,5]) [5, 4, 3, 2, 1]
By the time you are half-way through the list, you have swapped all the items; as you continue through the second half, you are swapping them all back to their original locations again.
Instead try
def reverse(lst):
i = 0 # first item
j = len(lst)-1 # last item
while i<j:
lst[i],lst[j] = lst[j],lst[i]
i += 1
j -= 1
return lst
This can be used in two ways:
a = [1,2,3,4,5]
reverse(a) # in-place
print a # -> [5,4,3,2,1]
b = reverse(a[:]) # return the result of reversing a copy of a
print a # -> [5,4,3,2,1]
print b # -> [1,2,3,4,5]
You are changing the list that you iterate on it (data_list) because of that it's not working , try like this:
def reverse(data_list):
length = len(data_list)
s = length
new_list = [None]*length
for item in data_list:
s = s - 1
new_list[s] = item
return new_list