Python Program to Reverse a List
Beginner · Lists
Reversing a list puts its elements in the opposite order, so the last element comes first and the first comes last. This program builds the reversed list with a loop that reads the original from its last index down to 0.
Program
Original list: [10, 20, 30, 40, 50] Reversed list: [50, 40, 30, 20, 10]
How it works
- The last index of a list is
len(numbers) - 1, which is 4 for a list of five elements. range(len(numbers) - 1, -1, -1)counts 4, 3, 2, 1, 0: the stop value -1 is not included, and the step -1 counts backwards.- Each element is appended to
reversed_listin that backwards order. - The original list is not changed, because the program builds a new list.
Other ways to write it
Using slicing, reversed() and reverse()
Using slicing: [50, 40, 30, 20, 10] Using reversed(): [50, 40, 30, 20, 10] The list itself is unchanged: [10, 20, 30, 40, 50] After numbers.reverse(): [50, 40, 30, 20, 10]
numbers[::-1] and reversed() give a reversed copy, while numbers.reverse() changes the list itself. Writing numbers = numbers.reverse() is a common mistake, because reverse() returns None.
Swapping from both ends in place
Reversed in place: [50, 40, 30, 20, 10]
Two positions move towards the middle, swapping as they go, so the list is reversed without making a second list.
Try it yourself
Reverse the list ["a", "b", "c", "d"] and check that the program works for strings too.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises