Skip to content

Q&A · Answered

How to remove duplicates from a list in Python

asked 9 months, 1 week ago 953 views 1 answer
3

I have a list with duplicate values. How do I remove them?

1 Answer

One accepted
29

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
my_list = [1, 2, 2, 3, 3, 3, 4]

# Convert to set (loses order)
unique = list(set(my_list))

# Preserve order (Python 3.7+)
unique = list(dict.fromkeys(my_list))

# Using list comprehension
seen = set()
unique = [x for x in my_list if not (x in seen or seen.add(x))]

# For objects, use id or custom key
unique_objects = list({obj.id: obj for obj in objects}.values())

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.