Hone

Lessons · Python · sets remove duplicates

A collection that refuses duplicates

A set holds each value at most once, and checks membership instantly.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Deduplicating, 'have I seen this', intersections of two lists, distinct counts. Sets do in one line what loops do in ten.

How to think about it

Ask: do I care about order or about duplicates? Duplicates gone, order irrelevant: set(). Need the order kept too: walk the list with a set as memory.

Worked example

tags = ["a", "b", "a", "c", "b"]
Repeats.
print(len(set(tags)))
3 distinct values.
print(set(tags) & {"b", "z"})
{"b"}: the intersection, in one operator.

Your turn

Is there any repeated value?

has_repeat = len(set(items))  len(items)

The trap

{} makes an empty dict, not an empty set. Use set().

Practise sets remove duplicates on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.