Practice: Reverse in Place
No extra list.
Here's your first practice problem. Reverse a list, without creating a second list, and without using the built in reverse. Pause the video, and think about how two pointers could help.

- Reverse a list
- No second list
- Pause and think
Swapping from the ends
Put one pointer at each end. Swap the two items, then move both pointers towards the middle. Stop when they meet. Python can swap two values in one line, with a comma. Run it. The list is reversed, using O of one extra space, and O of N time.
def reverse(items):
left, right = 0, len(items) - 1
while left < right:
items[left], items[right] = items[right], items[left]
left += 1
right -= 1
letters = ["a", "b", "c", "d", "e"]
reverse(letters)
print(letters)['e', 'd', 'c', 'b', 'a']
Built in versions
In real code, you'd usually just call the built in tools. List dot reverse reverses in place. Slicing with a step of minus one makes a reversed copy. And reversed gives you the items backwards, one at a time. But interviewers love asking you to write it yourself, to see how you think.
| key | value |
|---|---|
| a.reverse() | in place, O(1) space |
| a[::-1] | a reversed copy |
| reversed(a) | items backwards |
| Write it yourself | interview favourite |
Summary
Swap from both ends, and move inwards. That reverses a list in place, in O of N time and O of one space. Next, checking palindromes.
Key takeaways- Swap the ends
- Move inwards
- O(1) extra space