You are currently viewing How to reverse the List in Python

In previous articles related to lists, we have learned basic concepts of the list in python. We have also seen some of the operations that we can perform on Python lists. There are many logics that can be used to reverse items of a list in python. In this article, we will see some of those logics. let us see them one by one.

Reversing a Python List without using the built-in function

Here we are reversing the list without using any of the built-in function

my_list = [1,5, 2, 3, 4, 5]
my_dic={}
copylist=my_list[::-1]
print(copylist)

# output:
# original List  [1, 5, 2, 3, 4, 5]
# reversed list [5, 4, 3, 2, 5, 1]

A second method to reverse the list without using the built-in function.

my_list = [1,5, 2, 3, 4, 5]
num=[]
j=1
for i in my_list:
    num.append(my_list[len(my_list)-j])
    j=j+1
print(num)  

# output:
# original List  [1, 5, 2, 3, 4, 5]
# reversed list [5, 4, 3, 2, 5, 1]

Using builtin function to reverse a python list

Here we are using the builtin function to reverse the list

my_list = [1,5, 2, 3, 4, 5]
my_list.reverse()
print(my_list)

# output:
# original List  [1, 5, 2, 3, 4, 5]
# reversed list [5, 4, 3, 2, 5, 1]

You might be thinking of when to use which method? The answer is the first 2 methods I mentioned was to clear the logic of how reversing a list can work. The last method is using the Python builtin function. It depends on the situation, which one is applicable. Generally, for quick coding we use the inbuilt function.

That’s it Folks on this topic. Let us know your comments on this article in the comment box below. Kindly like our facebook page, follows us on twitter and subscribe to our YouTube channel for latest updates.

Leave a Reply