Back
+10 XP
Concept

Deduplicating Lists: `list(set())` Hack

The fastest way to purge duplicate elements from a list is to cast it into a set and back: `list(set(raw))`.

python
emails = ["a@x.com", "b@x.com", "a@x.com"]
unique = list(set(emails))
print(unique)  # ['a@x.com', 'b@x.com']

# 87. Deduplicating Lists: `list(set())` Hack The fastest way to purge duplicate elements from a list is to cast it into a set and back: `list(set(raw))`: ```python emails = ["a@x.com", "b@x.com", "a@x.com"] unique = list(set(emails)) print(unique) # ['a@x.com', 'b@x.com'] ``` The only catch: Sets do not preserve sequence order. If you need deduplication while keeping the exact original ordering, use `list(dict.fromkeys(emails))`.

Checkpoint

What is the single drawback of using `list(set(items))` to deduplicate?

Practice

Deduplicate `raw = [1, 2, 2, 3, 3, 3]` by converting to a set and back to a list in variable `cleaned`. Print `cleaned`.

Terminal
01
Tap code blocks below to assemble
Available Blocks