3
I have a list with duplicate values. How do I remove them?
Loading...
Q&A · Answered
I have a list with duplicate values. How do I remove them?
Accepted answer
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())Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.