PYTHON PROGRAMMING: REPLICATING THE REVERSE FUNCTION

John Okoye
2 min readApr 5, 2023

--

The Reverse function(method) is used to reverse the order of a list. It changes a list with the last element becoming the first element and vice versa.

# using list comprehension to populate a list
y = [x for x in range(6)]
print(y)
>>> [0, 1, 2, 3, 4, 5]
y.reverse()
print(y)
>>> [5, 4, 3, 2, 1, 0]
# just like that!

You can read more on the reverse method(function) on Geeks for Geeks.

Now, we want to replicate this function. We will go about it by:

  1. Creating new_list, an empty list. This list will be populated by appending elements from pa(the list to be reversed), in reverse order.
  2. To reference the last element of a list, we set the index to -1, and deduct 1 to reference subsequent elements. Hence, the declaration of b and assigning it a value of -1.
"""
this function, reverse, takes in pa, the list we are looking to reverse
"""
def reverse(pa = []):
new_list = []
b = -1

3. The for loop, as seen below, first appends the element, after which it decrements b. This continues till the elements of pa are exhausted, ensured by the range(len(pa))condition.

for i in range(len(pa)):
new_list.append(pa[b])
b = b - 1

4. By the end of the for loop, new_list contains the elements of pa, but in reverse order, while pa remains intact.

5. But, the reverse method modifies pa , therefore, this replica function should. Hence, the need to clear pa and extend it to include elements of new_list.

pa.clear() 
pa.extend(new_list)
return pa

Altogether, we have:

def reverse(pa = []):
new_list = []
b = -1
for i in range(len(pa)):
new_list.append(pa[b])
b = b - 1
pa.clear()
pa.extend(new_list)
return pa

Let us go ahead and test it:

y = [x for x in range(6)]
>>> [0, 1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'cherry']
print(fruits)
>>> ['apple', 'banana', 'cherry']
print(reverse(fruits))
>>> ['cherry', 'banana', 'apple']
print(fruits)
>>> ['cherry', 'banana', 'apple']
print(y)
>>> [0, 1, 2, 3, 4, 5]
print(reverse(y))
>>> [5, 4, 3, 2, 1, 0]
print(y)
>>> [5, 4, 3, 2, 1, 0]

And so, we come to the end of another one. Feel free to comment and share ideas. Thank you.

Thank you for reading!

--

--

John Okoye
John Okoye

Written by John Okoye

Data, Engineering, and Writing Enthusiast

No responses yet