Reverse a List
Reverse a list in Python without built-in methods.
List reversal teaches you about mutable vs immutable objects, in-place modifications, and space-time trade-offs. Understanding different reversal methods helps you choose the right approach for your specific use case.
📚 Concepts & Theory
Reversing a list is a fundamental operation in Python that can be accomplished through multiple approaches. Unlike strings, lists are mutable, meaning they can be modified in-place.
Key Distinction: In-Place vs Creating New List
Method 1: Slicing (Creates New List)
original = [1, 2, 3, 4, 5]
reversed_list = original[::-1] # [5, 4, 3, 2, 1]
# original is unchanged
Method 2: reverse() Method (In-Place)
numbers = [1, 2, 3, 4, 5]
numbers.reverse() # Modifies the list directly
# numbers is now [5, 4, 3, 2, 1]
Method 3: reversed() Function (Returns Iterator)
original = [1, 2, 3, 4, 5]
reversed_list = list(reversed(original))
Method 4: Manual Loop (Educational)
numbers = [1, 2, 3, 4, 5]
reversed_list = []
for num in numbers:
reversed_list.insert(0, num) # Insert at beginning
# Or: reversed_list = [num] + reversed_list
Method 5: Two-Pointer Swap (In-Place)
def reverse_in_place(lst):
left, right = 0, len(lst) - 1
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
Understanding the Trade-offs:
- Slicing [::-1]: Most Pythonic, creates new list O(n) space
- reverse(): Fastest in-place, modifies original O(1) space
- reversed(): Memory efficient iterator, good for large lists
- Manual loop: Educational, shows the logic clearly
🎯 Your Challenge
Write a function reverse_list without using reverse() or [::-1].
📝 Starter Code
def reverse_list(items):
pass
print(reverse_list([1, 2, 3]))
- Python has a slicing syntax that can reverse sequences
- The syntax is [start:stop:step]
- A step of -1 means go backwards
- This creates a new list, doesn't modify the original
- The simplest solution is just one line: [::-1]
Solution
def reverse_list(items):
result = []
for i in range(len(items)-1, -1, -1):
result.append(items[i])
return result
print(reverse_list([1, 2, 3]))
Explanation
This solution uses Python's slicing syntax [::-1] to create a new list with elements in reverse order. The step value of -1 tells Python to traverse the list backwards. This creates a shallow copy with reversed order, leaving the original list unchanged. While not the most space-efficient method, it's the most concise and Pythonic. Time complexity: O(n). Space complexity: O(n) for the new list. For in-place reversal, use the reverse() method instead.
⚠️ Common Mistakes to Avoid
- Confusing reverse() method (in-place) with reversed() function
- Expecting [::-1] to modify the original list
- Not assigning the result of [::-1] to a variable
- Using reversed() without converting to list
- Trying to use string methods on lists