Write A Python Program To Reverse A List
Chapter:
Python
Last Updated:
15-05-2023 15:00:50 UTC
Program:
/* ............... START ............... */
def reverse_list(lst):
return lst[::-1]
# Test the program
my_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list(my_list)
print(reversed_list)
/* ............... END ............... */
Output
Notes:
-
This Python program defines a function called reverse_list that takes a list as input. The goal of the program is to reverse the order of the elements in the list.
- Inside the reverse_list function, we use list slicing with a step of -1 ([::-1]). This means that we start at the end of the list and move towards the beginning, taking each element with a step of -1. By doing so, we effectively reverse the order of the elements in the list.
- In the test case, we create a list called my_list with the elements [1, 2, 3, 4, 5]. We then call the reverse_list function, passing my_list as the argument. The function reverses the list and returns it. Finally, we print the reversed list to the console.
- When you run this program, the output will be [5, 4, 3, 2, 1], which is the original list [1, 2, 3, 4, 5] reversed.
Tags
Write A Python Program To Reverse A List #Reversing a List in Python #How to Reverse a List in Python