datarekha

How do you reverse a list and remove duplicates in Python, and what are the performance implications of each approach?

The short answer

Reversing a list is O(n) whether you use slice notation or list.reverse(). Deduplication is O(n) with a set conversion but O(n²) if you check membership against a list. Understanding when order must be preserved changes which tool to reach for.

How to think about it

It looks like a throwaway question, but the interviewer is listening for the performance angle: the gap between O(n) set-based dedup and the O(n²) loop most people write first. And the order question — plain set versus dict.fromkeys — separates the candidates who know the stdlib idioms from the ones guessing.

A worked example

# Reversing — two ways, different memory profiles
nums = [1, 2, 3, 4, 5]
nums.reverse()                         # in place: O(n), O(1) extra, original gone
print("in-place reverse :", nums)

original = [10, 20, 30, 40]
print("reversed copy    :", original[::-1])   # O(n), keeps both
print("original intact  :", original)

# Deduplication — order is the deciding question
items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print("set dedup (order lost) :", sorted(set(items)))         # sorted only to print stably
print("dict.fromkeys (kept)   :", list(dict.fromkeys(items))) # first-seen order preserved
print("deduped + reversed     :", list(dict.fromkeys(items))[::-1])
in-place reverse : [5, 4, 3, 2, 1]
reversed copy    : [40, 30, 20, 10]
original intact  : [10, 20, 30, 40]
set dedup (order lost) : [1, 2, 3, 4, 5, 6, 9]
dict.fromkeys (kept)   : [3, 1, 4, 5, 9, 2, 6]
deduped + reversed     : [6, 2, 9, 5, 4, 1, 3]

The two dedup lines tell the whole story. set(items) removed the repeats but lost the order — I sorted it only to get a stable print; its real order is arbitrary. dict.fromkeys(items) removed the same repeats while keeping first-seen order3, 1, 4, 5, 9, 2, 6 — because dict keys are unique and insertion-ordered since 3.7. When order matters, that’s the idiom; when it doesn’t, set is marginally leaner.

When to use which

GoalToolTimeSpace
reverse in placelist.reverse()O(n)O(1)
reverse to a new listlst[::-1]O(n)O(n)
dedupe, order irrelevantlist(set(lst))O(n)O(n)
dedupe, order preservedlist(dict.fromkeys(lst))O(n)O(n)
dedupe + reverselist(dict.fromkeys(lst))[::-1]O(n)O(n)
Learn it properly Lists

Keep practising

All Python questions

Explore further

Skip to content