How to Reverse a List in Python?

How To Reverse A List In Python

The problem here is to write a program to reverse a list in Python.

Python is an interpreted, high-level and general-purpose programming language.

In computer science, a list or sequence is an abstract data type that represents a countable number of ordered values, where the same value may occur more than once. An instance of a list is a computer representation of the mathematical concept of a tuple or finite sequence; the infinite analog of a list is a stream.

In simple words, a list is collection of elements (strings, integers, objects).

How To Reverse A List In Python

array = [0, 10, 20, 40]
reverse_array  = []

print("Array before reversing : ", array)
for i in range(len(array)-1, -1,-1):
	reverse_array.append(array[i])

print("Array after reversing : ", reverse_array)
  

Output

How to Reverse a List in Python? $ python3 program.py
Array before reversing :  [0, 10, 20, 40]
Array after reversing :  [40, 20, 10, 0]
How to Reverse a List in Python? $ 

Output Image

How To Reverse A List In Python
Well there is another method, a very short method called slicing. You will like this one.

array = [0, 10, 20, 40]
print("Array before reversing : ", array)

array = array[::-1]

    
print("Array after reversing : ", array)
  
The result of this python code will be the same as it was for code before.

Try it you will get the same output. Much shorter, quicker and easy to remember.

Comments