0
0
PythonProgramBeginner · 2 min read

Python Program to Reverse a List

You can reverse a list in Python using slicing like reversed_list = original_list[::-1] or by using the reverse() method like original_list.reverse().
📋

Examples

Input[1, 2, 3, 4, 5]
Output[5, 4, 3, 2, 1]
Input['apple', 'banana', 'cherry']
Output['cherry', 'banana', 'apple']
Input[]
Output[]
🧠

How to Think About It

To reverse a list, think about flipping the order of elements so the last becomes first and the first becomes last. You can do this by reading the list from the end to the start or by swapping elements from the front and back until you reach the middle.
📐

Algorithm

1
Get the original list as input.
2
Create a new list by reading elements from the end to the start, or modify the original list in place by swapping elements.
3
Return or print the reversed list.
💻

Code

python
original_list = [1, 2, 3, 4, 5]
reversed_list = original_list[::-1]
print(reversed_list)
Output
[5, 4, 3, 2, 1]
🔍

Dry Run

Let's trace reversing the list [1, 2, 3, 4, 5] using slicing.

1

Original list

original_list = [1, 2, 3, 4, 5]

2

Apply slicing with step -1

reversed_list = original_list[::-1] results in [5, 4, 3, 2, 1]

3

Print reversed list

Output: [5, 4, 3, 2, 1]

IndexValue
45
34
23
12
01
💡

Why This Works

Step 1: Using slicing

The slicing syntax list[::-1] reads the list from the end to the start, creating a new reversed list.

Step 2: Using reverse() method

The reverse() method changes the original list by swapping elements from front and back until the middle is reached.

🔄

Alternative Approaches

Using reverse() method
python
original_list = [1, 2, 3, 4, 5]
original_list.reverse()
print(original_list)
This method reverses the list in place and does not create a new list.
Using a for loop
python
original_list = [1, 2, 3, 4, 5]
reversed_list = []
for item in original_list:
    reversed_list.insert(0, item)
print(reversed_list)
This builds a new reversed list by inserting each element at the front, but is less efficient.

Complexity: O(n) time, O(n) space

Time Complexity

Reversing a list requires visiting each element once, so it takes linear time proportional to the list size.

Space Complexity

Using slicing creates a new list, so it uses extra space proportional to the list size. The reverse() method works in place using constant extra space.

Which Approach is Fastest?

The reverse() method is fastest and uses less memory because it reverses the list in place. Slicing is simpler but uses extra memory.

ApproachTimeSpaceBest For
Slicing (list[::-1])O(n)O(n)When you want a new reversed list
reverse() methodO(n)O(1)When you want to reverse the list in place
For loop with insertO(n²)O(n)Learning purpose, less efficient
💡
Use slicing list[::-1] for a quick and easy way to reverse a list without changing the original.
⚠️
Trying to assign the result of list.reverse() to a variable, but it returns None because it reverses in place.