Editor

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

reverse_a_list.py
numbers = [10, 20, 30, 40, 50] # or: numbers = input("Enter items: ").split()
reversed_list = []
# Start at the last index and count down to 0
for i in range(len(numbers) - 1, -1, -1):
reversed_list.append(numbers[i])
print("Original list:", numbers)
print("Reversed list:", reversed_list)
Output
Original list: [10, 20, 30, 40, 50]
Reversed list: [50, 40, 30, 20, 10]

How it works

  1. The last index of a list is len(numbers) - 1, which is 4 for a list of five elements.
  2. 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.
  3. Each element is appended to reversed_list in that backwards order.
  4. 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, reversed() and reverse()
numbers = [10, 20, 30, 40, 50]
print("Using slicing:", numbers[::-1])
print("Using reversed():", list(reversed(numbers)))
print("The list itself is unchanged:", numbers)
numbers.reverse() # reverses the list in place and returns None
print("After numbers.reverse():", numbers)
Output
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

Swapping from both ends in place
numbers = [10, 20, 30, 40, 50]
left = 0
right = len(numbers) - 1
while left < right:
numbers[left], numbers[right] = numbers[right], numbers[left]
left += 1
right -= 1
print("Reversed in place:", numbers)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises