Here is a Python program that shows reversing a list: built-in and custom methods.

Reverse a list in Python
Photo by Anete Lusina on Pexels.com

Table of contents

  1. CUSTOM Method
  2. Built-in method

CUSTOM Method

Here’s a class called RevIter that takes a list and reverses each item using the pop method. The init method initializes the argument, the iter method iterates through the list, and the next method processes each item. The pop method selects the last item to process first.

class RevIter:
    def __init__(self, iterable):
        self.iterable = iterable  # Stores the list
    def __iter__(self):
        return self
    def __next__(self):
        try:
            return self.iterable.pop()  # Removes and returns the last element
        except IndexError:
            raise StopIteration
            
# Usage of the function
a=[]
for i in RevIter([1, 2, 3, 4, 5]):
    a.append(i)
  
print(a)  # Output: [5, 4, 3, 2, 1]

Output

[5, 4, 3, 2, 1]

Built-in method

Here I used a built-in method called reversed. To store the output, I have assigned the variable reversed_list. Then, using the for loop, read each item and write it to the output.

my_list=[1,2,3,4]
reversed_list = reversed(my_list)
output=[]
for item in reversed_list:
    output.append(item)
    
print(output)     

Output

[4, 3, 2, 1]


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Conclusion

  • You can reverse a list using a custom function or the built-in reversed() method.
  • The custom function uses the pop() method to reverse.
  • The built-in method(reversed) returns an iterator that iterates over the list in reverse order.
  • Both methods produce the same outcome.